﻿function ExecuteService(params, url, callbackSuccess, callbackError)
{
    $.ajax({
      type: "POST",
      url: url,
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      data: params,
      success: callbackSuccess,
      error: callbackError
    });                                        
}
/**/
function CheckPasswordAndLogin(inputLogin, inputPassword, callbackResult, callbackError)
{
    var login = $(inputLogin)[0].value;
    var password = $(inputPassword)[0].value;
    
    if (login.length > 0 && password.length > 0)
    {            
        var params = '{"login":"'+login+'", "password":"'+password+'"}';
        ExecuteService(
            params, 
            "HabraEditor.asmx/CheckPasswordAndLogin",
            callbackResult,
            callbackError
        );       
    }
    else
    {
        alert("Укажите логин и пароль")
    }
}
function onCheckPasswordAndLogin(msg)
{    
    if (msg.d.result)
    {
        UpdateSaveSlots(true);
    }
    else 
    {
        alert("Нет такого пользователя или пароль введен с ошибкой");
    }
} 
function RegisterAndLogin(inputLogin, inputPassword, callbackResult, callbackError)
{
    var login = $(inputLogin)[0].value;
    var password = $(inputPassword)[0].value;
    
    if (login.length > 0 && password.length > 0)
    {            
        var params = '{"login":"'+login+'", "password":"'+password+'"}';
        ExecuteService(
            params, 
            "HabraEditor.asmx/RegisterAndLogin",
            callbackResult,
            callbackError
        );       
    }
    else
    {
        alert("Укажите логин и пароль")
    }
}
function onRegisterAndLogin(msg)
{    
    if (msg.d.result)
    {
        UpdateSaveSlots(true);
    }
    else 
    {
        alert("Такой логин уже используется, попробуйте ввести другой");
    }
} 
function UpdateSaveSlots(show)
{
    if (show)
    {
        var params = '{}';
        ExecuteService(
            params, 
            "HabraEditor.asmx/GetSaveSlots",
            onGetSaveSlots,
            onError
        );               
    }
    else
    {
        $("#saveSlots").hide();
    }
}
function onGetSaveSlots(Msg)
{
    $("#saveTextC")[0].value = Msg.d.c.ShortSlotName;
    $("#saveTextM")[0].value = Msg.d.m.ShortSlotName;
    $("#saveTextY")[0].value = Msg.d.y.ShortSlotName;
    $("#saveTextK")[0].value = Msg.d.k.ShortSlotName;
    $("#saveSlots").show();
    $("#loginP").hide();
}
/**/
function SaveDocument(shortName)
{
    var selected = $("#savePanel").data("selected");
    if (selected != null)
    {            
        var introText = $("#introText")[0].value.replace(/\"/gm, "&quot;").replace(/\\/gm, "&#92;");
        if (introText.length > 50000)
        {
            alert("Слишком большой текст вступления (>50000)");        
            return;
        }
        var mainText = $("#mainText")[0].value.replace(/\"/gm, "&quot;").replace(/\\/gm, "&#92;");
        if (mainText.length > 150000)
        {
            alert("Слишком большой основной текст (>150000)");
            return;
        }
        var habracutText = $("#habracutText")[0].value.replace(/\"/gm, "&quot;").replace(/\\/gm, "&#92;");
        if (habracutText.length > 255)
        {
            alert("Слишком большой текст хабраката (>255)");
            return;
        }
        var shortSlotName = shortName.replace(/\"/gm, "&quot;").replace(/\\/gm, "&#92;"); 
        //$("#" + selected + " input")[0].value.replace(/\"/gm, "&quot;").replace(/\\/gm, "&#92;");
        if (shortSlotName.length > 255)
        {            
            alert("Слишком большой текст слота сохранения (>255)");
            return;
        }

        var slotChar = $("#" + selected + " span").html();
            
        if (introText.length > 0 || mainText.length > 0)
        {                        
            var params = '{"data":{"Slot":"'+slotChar+'", "ShortSlotName":"'+shortSlotName+'", "Data":{"HabracutText":"'+habracutText+'", "IntroText":"'+introText+'", "MainText":"'+mainText+'", "IsPreview":"false"}}}';
            ExecuteService(
                params, 
                "HabraEditor.asmx/SaveDocument",
                onSaveDocument,
                onError
            );       
            $("#" + selected + " input")[0].value = shortName;
        } else
        {
            alert("Введите хоть что-нибудь");
        }    
    }
    else
    {
        alert("Выберите слот");
    }
}
function onSaveDocument(Msg)
{
    if (Msg.d == 0)
    {    
        $("#savePanel").hide();
    } else if (Msg.d == 1)
    {
        $("#saveSlots").hide();
        $("#loginP").show();    
    } else if (Msg.d == 2)
    {
    } else if (Msg.d == 3)
    {
        alert("Извините, но при загрузке произошла ошибка");
    }
}
function LoadDocument()
{
    var selected = $("#savePanel").data("selected");
    if (selected != null)
    {
        var slotChar = $("#" + selected + " span").html();
        var params = '{"data":{"Slot":"'+slotChar+'"}}';
        ExecuteService(
            params, 
            "HabraEditor.asmx/LoadDocument",
            onLoadDocument,
            onError
        );       
    }
    else
    {
        alert("Выберите слот");
    }
}
function onLoadDocument(Msg)
{
    if (Msg.d.result == 0)
    {
        $("#introText")[0].value = Msg.d.IntroText;
        $("#mainText")[0].value = Msg.d.MainText;
        $("#habracutText")[0].value = Msg.d.CutText;
        $("#savePanel").hide();
    } else if (Msg.d.result == 1)
    {
        $("#saveSlots").hide();
        $("#loginP").show();    
    } else if (Msg.d.result == 2)
    {
        alert("Этот слот пуст");    
    } else if (Msg.d.result == 3)
    {
        alert("Извините, но при загрузке произошла ошибка");
    }
}
/**/
function GenerateText(isPreview, callbackResult, callbackError)
{        
    var introText = $("#introText")[0].value.replace(/\"/gm, "&quot;").replace(/\\/gm, "&#92;");
    var mainText = $("#mainText")[0].value.replace(/\"/gm, "&quot;").replace(/\\/gm, "&#92;");
    var habracutText = $("#habracutText")[0].value.replace(/\"/gm, "&quot;").replace(/\\/gm, "&#92;");
        
    if (introText.length > 0 || mainText.length > 0)
    {                        
        var params = '{"data":{"HabracutText":"'+habracutText+'", "IntroText":"'+introText+'", "MainText":"'+mainText+'", "IsPreview":"'+isPreview+'"}}';
        ExecuteService(
            params, 
            "HabraEditor.asmx/GenerateText",
            callbackResult,
            callbackError
        );       
    } else
    {
        alert("Введите хоть что-нибудь");
    }
}
function onGenerateText(Msg)
{
    $("#genText")[0].value = Msg.d;
    $("#genTextPanel").show(100);    
    var copied = $.clipboard(Msg.d);
    if (copied)
        $("#clipWarn").show();
}        
function onGeneratePreview(Msg)
{
    $("#previewText").html(Msg.d);
    $("#previewPanel").show(100);    
}        
function onError(XMLHttpRequest, textStatus, errorThrown)
{
    alert("error");
}        
/**/
function ReplaceText(newTemplate, linkText)
{            
    var selText = $("#mainText").getSelection().text;
    if (selText.length == 0)
        selText = $("#introText").getSelection().text;
    
    var selectedMain = $("#mainText").data("selected");
        
    var newText = newTemplate.replace(/_SELTEXT_/g, selText);
    var newText = newText.replace(/_LINKTEXT_/g, linkText);
        
    if (selectedMain == "true")
        $("#mainText").replaceSelection(newText);
    else 
        $("#introText").replaceSelection(newText);
}
function TransliterateReverse(str)
{
    var res = str;
    
    var _dic = new Array(['щ', "sch"], ['ч', "ch"], ['ш', "sh"], ['ё', "yo"], 
    ['ж', "zh"], ['ю', "yu"], ['я', "ya"], ['а', "a"], ['б', "b"], ['в', "v"], ['г', "g"], 
    ['д', "d"], ['е', "e"], ['з', "z"], ['и', "i"], ['й', "y"], ['к', "k"], ['л', "l"], 
    ['м', "m"], ['н', "n"], ['о', "o"], ['п', "p"], ['р', "r"], ['с', "s"], ['т', "t"], 
    ['у', "u"], ['ф', "f"], ['х', "h"], ['ц', "c"], ['ы', "i"], ['ь', "'"], ['э', "e"],
    ['Щ', "Sch"], ['Ч', "Ch"], ['Ш', "Sh"], ['Ё', "Yo"], 
    ['Ж', "Zh"], ['Ю', "Yu"], ['Я', "Ya"], ['А', "A"], ['Б', "B"], ['В', "V"], ['Г', "G"], 
    ['Д', "D"], ['Е', "E"], ['З', "Z"], ['И', "I"], ['Й', "Y"], ['К', "K"], ['Л', "L"], 
    ['М', "M"], ['Н', "N"], ['О', "O"], ['П', "P"], ['Р', "R"], ['С', "S"], ['Т', "T"], 
    ['У', "U"], ['Ф', "F"], ['Х', "H"], ['Ц', "C"], ['Ы', "I"], ['Ь', "'"], ['Э', "E"]);
    
    var len = _dic.length;
    
    for(i = 0; i < len; i++)
    {
        var exp = RegExp(_dic[i][1], 'gm');
        res = res.replace(exp, _dic[i][0]);
    }
    return res;
}
/**/
$(document).ready
(
    function() {
        $.clipboardReady(function() { }, { swfpath: "js/jquery.clipboard.swf", debug: false });
        $("#introPanel").corner();
        $("#mainPanel").corner();
        $("#previewPanel2").corner();
        $("#genTextPanel2").corner();
        $("#floatPanel").corner();
        $("#charmapPanel").corner();
        $("#savePanel").corner();
        $("#mp-input").corner();
        $("#mp-btn").corner();
        $("#mp-cmd").corner();
        $("#savePanel li[@id*=slot]").corner();

        $("input[type=text]", "#mp-input").each(function() {
            $(this).data("def", $(this).attr("value"));
            $(this).data("clear", "true");
            $(this).addClass("def-value");
        });
        $("input[type=text]", "#mp-input").bind("focus", function() {
            if ($(this).data("clear") == "true") {
                $(this).attr("value", "");
                $(this).removeClass("def-value");
            }
        });
        $("input[type=text]", "#mp-input").bind("blur", function() {
            var def = $(this).data("def");
            if ($(this).attr("value") != "") {
                $(this).data("clear", "false");
            }
            else {
                $(this).addClass("def-value");
                $(this).attr("value", def);
                $(this).data("clear", "true");
            }
        });


        $("#syntaxFrame").data("shown", "false");
        $("#showSavePanel, #closeSP").click(function() { $("#savePanel").toggle(300); })
        $("#showHSPanel").click(function() {
            if ($("#syntaxFrame").data("shown") == "false") {
                $("#syntaxFrame")[0].src = "http://source.virtser.net";
                $("#syntaxFrame").data("shown", "true");
            }
            $("#syntaxPanel").toggle(300);
        })
        $("#savePanel li[@id*=slot]").click(function() {
            $("#savePanel li[@id*=slot] input").css("border", "solid 0px #FFF");
            $("#savePanel #" + this.id + " input").css("border", "solid 2px green");
            $("#savePanel").data("selected", this.id);
        })
        $("#charmapPanel span").css("cursor", "pointer");
        $("#charmapPanel span").click(function() { ReplaceText($(this).attr("title")); })
        $("#mainText").focus(function() {
            $(this).css("background-color", "#FFF");
            $("#introText").css("background-color", "#ECF2F9");
            $("#mainText").data("selected", "true");
            $("#introText").data("selected", "false");
        })
        $("#introText").focus(function() {
            $(this).css("background-color", "#FFF");
            $("#mainText").css("background-color", "#ECF2F9");
            $("#mainText").data("selected", "false");
            $("#introText").data("selected", "true");
        })

        $("#getText").click(function() {
            GenerateText(false, onGenerateText, onError);
        })
        $("#getPreview").click(function() {
            GenerateText(true, onGeneratePreview, onError);
        })
        $("#hideGenText").click(function() { $("#genTextPanel").hide(100); })
        $("#hideSyntaxPanel").click(function() { $("#syntaxPanel").hide(100); })
        $("#hidePreviewPanel").click(function() { $("#previewPanel").hide(100); })
        $("#insertLink").click(function() {
            ReplaceText('<a title="" href="_LINKTEXT_">_SELTEXT_</a>', $("#Link")[0].value);
        })
        $("#transliterate").click(function() {
            var selText = $("#mainText").getSelection().text;
            if (selText.length == 0)
                selText = $("#introText").getSelection().text;

            var newText = TransliterateReverse(selText);

            var selectedMain = $("#mainText").data("selected");

            if (selectedMain == "true")
                $("#mainText").replaceSelection(newText);
            else
                $("#introText").replaceSelection(newText);
        })
        $("#replaceLtGt").click(function() {
            var selText = $("#mainText").getSelection().text;
            if (selText.length == 0)
                selText = $("#introText").getSelection().text;

            var newText = selText.replace(/</gm, "&#60;").replace(/>/gm, "&#62;");

            var selectedMain = $("#mainText").data("selected");

            if (selectedMain == "true")
                $("#mainText").replaceSelection(newText);
            else
                $("#introText").replaceSelection(newText);
        })
        $("input[@id*=code]").click(function() {
            var tagOpen = '<' + this.value + '>';
            var tagClose = '</' + this.value + '>';
            ReplaceText(tagOpen + "_SELTEXT_" + tagClose);
        })
        $("input[@id*=insertVideo]").click(function() {
            var tagOpen = '<' + this.value + '>';
            var tagClose = '</' + this.value + '>';
            var elId = "#" + this.value;
            if ($(elId)[0].value.length > 0)
                ReplaceText(tagOpen + "_LINKTEXT_" + tagClose, $(elId)[0].value);
            else
                ReplaceText(tagOpen + "_SELTEXT_" + tagClose);
        })
        $("input[@id*=singleCode]").click(function() {
            var tag = '<' + this.value + ' />';
            ReplaceText(tag);
        })
        $("input[@id*=linesCode]").click(function() {
            var selText = $("#mainText").getSelection().text;
            if (selText.length == 0)
                selText = $("#introText").getSelection().text;

            var newText = selText.replace(/\r\n/g, "</li><li>");
            newText = newText.replace(/\n/g, "</li><li>");

            var tagOpen = '<' + this.value + '>\r\n<li>';
            var tagClose = '</li>\r\n</' + this.value + '>';
            newText = tagOpen + newText + tagClose;

            var selectedMain = $("#mainText").data("selected");

            if (selectedMain == "true")
                $("#mainText").replaceSelection(newText);
            else
                $("#introText").replaceSelection(newText);
        })
        $("#insertImage").click(function() {
            ReplaceText('<img title="" border="0" alt="_SELTEXT_" src="_LINKTEXT_"/>', $("#Image")[0].value);
        })
        $("input[@id*=res]").click(function() {
            $("#previewPanel2").css("width", this.value + "px");
        })
        $("#insertUser").click(function() {
            var selText = $("#mainText").getSelection().text;
            if (selText.length == 0)
                selText = $("#introText").getSelection().text;
            var linkText = $("#User")[0].value;

            var user = "";

            if (selText.length > 0)
                user = selText;
            else if (linkText.length > 0)
                user = linkText;

            var selectedMain = $("#mainText").data("selected");
            var newText = '<hh user="' + user + '" />';

            if (selectedMain == "true")
                $("#mainText").replaceSelection(newText);
            else
                $("#introText").replaceSelection(newText);
        })

        $("#cmdLogin").click(function() {
            CheckPasswordAndLogin("#txtLogin", "#txtPassword", onCheckPasswordAndLogin, onError);
        })
        $("#cmdRegister").click(function() {
            RegisterAndLogin("#txtLogin", "#txtPassword", onRegisterAndLogin, onError);
        })
        $("#cmdSave").click(function() {
            var selected = $("#savePanel").data("selected");
            var slotName = $("#" + selected + " input")[0].value;
            var shortName = prompt("Введите короткое имя для слота сохранения", slotName);
            if (shortName)
                SaveDocument(shortName);
        })
        $("#cmdLoad").click(function() {
            var answer = confirm("Уверены, что хотите загрузить другие данные?");
            if (answer)
                LoadDocument();
        })
    }
);
