﻿/**
 * Site Helper
 * 
 * 
 * <pre>
 * Использование:
 * http://host/path/to/doc.html#site_helper=on | http://host/path/to/#site_helper=on
 * 
 * Допустмые переменные:
 * Имя пользователя: user=[имя пользователя]
 *                   Прим. user=azazel -- по умолчанию undefined
 * Цвет записки:     color=#RGB|#RRGGBB|rgb(rrr, ggg, bbb)|[назвение цвета]. 
 *                   Прим. color=red  -- по умолчанию #FFC
 * Цвет линейки:     rcolor=#RGB|#RRGGBB|rgb(rrr, ggg, bbb)|[назвение цвета]
 *                   Прим. rcolor=red  -- по умолчанию blue
 * 
 * Также принимает переменные, но не желательно:
 * xhrURL
 * xhrMethod
 * 
 * Не допустимы переменные:
 * v 
 * 
 * Пример:
 * http://host/path/to/#site_helper=on;user=admin;color=#FCC;rcolor=red
 * </pre>
 * 
 * @author A.Z.Production <azazel.production@gmail.com>
 * @license LGPL
 * @version 1.0
 * @depend jquery.js, 
 *         ui.core.js, 
 *         ui.draggable.js
 * @todo   * Если перейти в полноэкранный режим (размер документа увеличится), 
 *         то вертикальные линейки будут короче, чем надо
 *         * При горизонтальном скролле горизонтальные линейки не перемешаются
 *         * При изменеии разрешения, если разметка плавающая, 
 *         все становится не туда куда надо
 *         * Заменить текст в меню иконками
 *         * Сделать привязку к html элементам (и)вместо x,y|left,top 
 */

$(document).ready(function(){
    var cnf = {
            // Измените настройки для себя
            xhrURL: '/translate/site_helper/index.php',
            // Только GET
            xhrMethod: 'GET',
            user: 'undefined',
            color: '#FFC',
            rcolor: 'blue',
            v: {
                refreshTime: new Date().getTime(),
                refreshDelta: 5000 //msec
            }
        };
            
    function addNote(e) 
    {
       container.append('<div id="site_helper_note-' + e[0] + '" class="site_helper_note" style="background-color:' + e[4] + ';position:absolute;left:' + e[1] + ';top:' + e[2] + '"><span class="author">' + e[3] + '</span><span class="text">' + e[5] + '</span></div>');
       $('#site_helper_note-' + e[0]).hide()
                                     .css('opacity', '0.5')
                                     .fadeIn()
                                     .draggable(drag_object)
                                     .mouseover(function(){
                                         $(this).css({opacity: 1});
                                     })
                                     .mouseout(function(){
                                         $(this).css({opacity: 0.5});
                                     })
                                     ;
    }
    
    function addNoteToList(e)
    {
        $('#site_helper_container').append('<div id="site_helper_note_list_item-' + e[0] + '" class="site_helper_note_list_item" style="background-color:' + e[4] + ';"><span class="author">' + e[3] + '</span><span class="text">' + e[5] + '</span>' +
        ((document.location.href == e[6] + document.location.hash)?' <a href="javascript:void(0);" id="site_helper_hl-' + e[0] + '" class="site_helper_hl" title="Найти объект">#</a>':' <a href="' +  e[6] + document.location.hash + '" title="Перейти на страницу">&rarr;</a>') + 
        '</div>');
        //hlTarget
    }
    
    function addRuller(e)
    {
        // [null, '0px', '0px', cnf.color, 0];
        var placeholder = ((e[4] != 1)?hor_rullercontainer:ver_rullercontainer);
        
        placeholder.append('<div id="site_helper_ruller-' + e[0] + '" class="site_helper_ruller' + ((e[4] == 1)?'_vertical':'_horizontal') + '" style="border-color:' + e[3] + ';left:' + e[1] + ';top:' + e[2] + ';' + ((e[4] == 1)?'height:' + $(document).height() + 'px;':'width:100%;') + '" title="' + ((e[4] == 1)?'Слева ' + e[1]:'Сверху ' + e[2]) + '">&nbsp;</div>');
        return $('#site_helper_ruller-' + e[0]).hide()
                                        .css('opacity', '0.3')
                                        .fadeIn()
                                        .draggable(((e[4] == 1)?drag_hor_ruller:drag_ver_ruller))
                                        .dblclick(ruller_dblclick)
                                        .mouseover(function(){
                                            $(this).css({opacity: 1});
                                        })
                                        .mouseout(function(){
                                            $(this).css({opacity: 0.3});
                                        })
                                        ;
    }
    
    function xhrEditNote(e) 
    {
        var ee = {
            func: 'edit',
            id: e[0],
            url: document.location.href.replace(document.location.hash, ''),
            x: e[1],
            y: e[2],
            user: e[3],
            color: e[4],
            note: e[5]
        };
        
        return $.ajax({
           url: cnf.xhrURL,
           type: cnf.xhrMethod,
           data: ee,
           cache: false,
           async: false
        }).responseText;
    }
    
    function xhrAuth() 
    {
        return $.ajax({
           url: cnf.xhrURL,
           type: cnf.xhrMethod,
           data: {func: 'auth', user: cnf.user},
           cache: false,
           async: false
        }).responseText == '1';
    }
    
    function xhrRemoveNote(id) 
    {
        return $.ajax({
           url: cnf.xhrURL,
           type: cnf.xhrMethod,
           data: {func: 'remove', id: id},
           cache: false,
           async: false
        }).responseText;
    }
    
    function xhrGetData(url)
    {
        return $.ajax({
           url: cnf.xhrURL,
           type: cnf.xhrMethod,
           data: {func: 'data', url: url},
           cache: false,
           async: false
        }).responseText;
    }
    
    function xhrGetRullers(url)
    {
        return $.ajax({
           url: cnf.xhrURL,
           type: cnf.xhrMethod,
           data: {func: 'rullers', url: url},
           cache: false,
           async: false
        }).responseText;
    }
    
    function xhrMatchData(url)
    {
        return $.ajax({
           url: cnf.xhrURL,
           type: cnf.xhrMethod,
           data: {func: 'match', url: url},
           cache: false,
           async: false
        }).responseText;
    }
    
    function xhrRemoveRuller(id)
    {
        return $.ajax({
           url: cnf.xhrURL,
           type: cnf.xhrMethod,
           data: {func: 'removeruller', id: id},
           cache: false,
           async: false
        }).responseText;
    }
    
    function xhrEditRuller(e)
    {
        var ee = {
            func: 'editruller',
            id: e[0],
            url: document.location.href.replace(document.location.hash, ''),
            x: e[1],
            y: e[2],
            color: e[3],
            vertical: e[4]
        };
        
        return $.ajax({
           url: cnf.xhrURL,
           type: cnf.xhrMethod,
           data: ee,
           cache: false,
           async: false
        }).responseText;
    } 
    
    function hlTarget(id)
    {
        var bc = $('#site_helper_note-' + id).css('border-color');
        $('#site_helper_note-' + id).animate({
            opacity: 1,
            "left": "+=25px"
        }, 100)
        .animate({
            "left": "-=50px"
        }, 200)
        .animate({
            "left": "+=25px"
        }, 100)
    }
    
    var click_function = function(event, e){
       var note = window.prompt('Заметка', $(event.target).text());
       if (note == ''){
           xhrRemoveNote($(event.target).parent().attr('id').split('-')[1]);
           $(event.target).parent().fadeOut().remove();
       } else {
           xhrEditNote([
              $(event.target).parent().attr('id').split('-')[1],
              $(event.target).parent().css('left'),
              $(event.target).parent().css('top'),
              $(event.target).parent().children('span.author').text(),
              $(event.target).parent().css('background-color'),
              note
           ]);
           $(event.target).text(note);
       }
    }
    
    var ruller_dblclick = function(){
        xhrRemoveRuller($(this).attr('id').split('-')[1]);
        $(this).remove();
    }
    
    var drag_object = {
        stop: function(event) {
           xhrEditNote([
              $(this).attr('id').split('-')[1],
              $(this).css('left'),
              $(this).css('top'),
              $(this).children('span.author').text(),
              $(this).css('background-color'),
              $(this).children('span.text').text()
           ]);
        },
        handle: 'span.author'
    };
    
    var drag_hor_ruller = {
        axis: 'x',
        stop: function(event) {
           //$(this).css('line-height', 'auto');
           $(this).html('&nbsp;');
           $(this).attr('title', 'Слева ' + $(this).css('left'));
           xhrEditRuller([
              $(this).attr('id').split('-')[1],
              $(this).css('left'),
              $(this).css('top'),
              $(this).get()[0].style.borderLeftColor,
              1
           ]);
        },
        drag: function(event){
            $(this).html(' ' + $(this).css('left'));
        },
        start: function(){
            //alert();
            //alert($(this).height());
            $(this).css('line-height', $(this).height() + 'px');
        }
    };
    
    var drag_ver_ruller = {
        axis: 'y',
        stop: function(event) {
           $(this).html('&nbsp;');
           $(this).attr('title', 'Сверху ' + $(this).css('top'));
           xhrEditRuller([
              $(this).attr('id').split('-')[1],
              $(this).css('left'),
              $(this).css('top'),
              $(this).get()[0].style.borderTopColor,
              0
           ]);
        },
        drag: function(event){
            $(this).html($(this).css('top'));
        }
    };
    
    if (window.location.hash.indexOf('site_helper=on') == -1) {
        return;
    }
    
    var tcnf = window.location.hash.replace(/^#/,'').split(';');

    for (var i = 0;i < tcnf.length;i++){
        var kv = tcnf[i].split('=');
        cnf[kv[0]] = kv[1];
    }
    
    if (!xhrAuth()) {
        return;
    }
    
    $('body:first').append('<div id="site_helper_all_cover_element">' + 
                             '<div id="site_helper_menu">' +
                             '<a href="javascript:void(0);" id="site_helper_menu_toggle">«</a>' +
                               '<a href="javascript:void(0);" id="site_helper_refresh">обновить</a>' +
                               '<a href="javascript:void(0);" id="site_helper_menu_add_note">добавить заметку</a>' +
                               '<a href="javascript:void(0);" id="site_helper_menu_list_notes">список заметок</a>' +
                               '<a href="javascript:void(0);" id="site_helper_menu_add_ruller">добавить линейку</a>' +
                             '</div>'+
                             '<div id="site_helper_container">' +
                             '</div>'+
                             '<div id="site_helper_container_ver_rullers" style="left:0px;top:0px;position:fixed;width:100%;height:auto">' +
                             '</div>'+
                             '<div id="site_helper_container_hor_rullers" style="left:0px;top:0px;width:100%;height:auto">' +
                             '</div>'+
                           '</div>');
    /*
    $('body:first').append('<div id="site_helper_all_cover_element2"></div>');
    
    $('#site_helper_all_cover_element2').css({
       'background-color': '#000',
       'opacity': '0.5',
       'position': 'fixed',
       'left': '0px',
       'top': '0px',
       'width': '100%',
       'height': '100%',
       'z-index': '1000'
    });
    */
    var container = $('#site_helper_all_cover_element');
    var ver_rullercontainer = $('#site_helper_container_ver_rullers');
    var hor_rullercontainer = $('#site_helper_container_hor_rullers');
    
    container
    .css({
        display: 'block',
        position: 'absolute',
        left: '0px',
        top: '0px',
        background: 'transparent',
        width: '100%',
        height: 'auto'
    });
    
    $('#site_helper_refresh').click(function(){
        if (new Date().getTime() >= cnf.v.refreshDelta + cnf.v.refreshTime) {
            refreshData();
            cnf.v.refreshTime = new Date().getTime();
        } else {
            alert('Пожалуйста, подождите ещё ' + (cnf.v.refreshDelta + cnf.v.refreshTime - new Date().getTime())/1000 + ' c.');
        }
    });
    
    $('#site_helper_menu_add_note').click(function(){
       var note = window.prompt('Заметка', '');
       if (!note) {
           return;
       }
        if (note != '') {
            var data = [
                null,
                Math.round(Math.random()*500) + 'px',
                Math.round(Math.random()*500) + 'px',
                cnf.user,
                cnf.color,
                note
            ]; 
            
            data[0] = xhrEditNote(data);
            
            addNote(data);
            $('#site_helper_note-' + data[0] + ' span.text').click(click_function);  
        }
    });
    
    $('#site_helper_menu_list_notes').click(function(){
        if ($('#site_helper_container').text() != '') {
           $('#site_helper_container').fadeOut().text('');
           return;
        } 
        var url = window.prompt('Базовый URL', document.location.href.replace(document.location.hash, ''));
        if (!url) {
           return;
        }
        if (url != '') {
            $('#site_helper_container').hide();
            var data = xhrMatchData(url);
            $('#site_helper_container').html('');
            $.each(data.split(/\r\n/), function(i, e){
                e = e.split('|');
                if (e[0]) {
                    addNoteToList(e);
                }        
            });
            $('#site_helper_container').fadeIn();

            $('#site_helper_container .site_helper_hl').click(function(){
                //alert(hlTarget);
                hlTarget($(this).attr('id').split('-')[1]);
                //alert('');
            });
        }
    });
    
    $('#site_helper_menu_toggle').toggle(function(){
        $(this).text('»')
               .parent()
               .css('opacity', '0.5')
               .end()
               .siblings()
               .fadeOut();
        $('#site_helper_container').fadeOut();
    },function(){
        $(this).text('«')
               .parent()
               .css('opacity', '1')
               .end()
               .siblings()
               .fadeIn();
        $('#site_helper_container').fadeIn();
    });
    
    
    $('#site_helper_menu_add_ruller').click(function(){
        var data = [null, '0px', '0px', cnf.rcolor, 0];
        if (window.confirm('Вертикальная линейка?')) {
            data[4] = 1;
            data[1] = Math.round(Math.random()*500) + 'px';
        } else {
            data[2] = Math.round(Math.random()*500) + 'px';
        }
        
        data[0] = xhrEditRuller(data);
        
        addRuller(data).stop().css('opacity', '1').fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200);
    });
    
    function refreshData()
    {
        $('#site_helper_all_cover_element .site_helper_ruller_vertical').remove();
        $('#site_helper_all_cover_element .site_helper_ruller_horizontal').remove();
        $('#site_helper_all_cover_element .site_helper_note').remove();
        $('#site_helper_all_cover_element .site_helper_note_list_item').remove();
        data = xhrGetData(document.location.href.replace(document.location.hash, ''));
        
        $.each(data.split(/\r\n/), function(i, e){
            e = e.split('|');
            if (e[0]) {
                addNote(e);
            }
        });
        
        $('#site_helper_all_cover_element div.site_helper_note span.text').click(click_function);
        $('#site_helper_all_cover_element div.site_helper_note').draggable(drag_object);
        
        data = xhrGetRullers(document.location.href.replace(document.location.hash, ''));
        
        $.each(data.split(/\r\n/), function(i, e){
            e = e.split('|');
            if (e[0]) {
                addRuller(e);
            }
        });
    }
    
    refreshData();
    
});










// EOF
