﻿
// E-MAIL на администратора на сайта (тук ще идват писмата с грешките)
    var adminEmail = adminEmail || 're'+'g'+'@'+'edi'+'tor'+'.'+'bg';

// Избор на комбинациите от клавишите за извикването на услугата
    var pr_alt = pr_alt || false; // комбинация ALT + ENTER
    var pr_shift = pr_shift || true; // комбинация SHIFT + ENTER
    var pr_ctrl = pr_ctrl || false; // комбинация CTRL + ENTER

// Максимално количество маркирани символи
    var maxSelectedTextWidth = maxSelectedTextWidth || 150;

// Текстови съобщения
    var selectedTextFalseAlert = selectedTextFalseAlert || "Грешка!: максималното количество маркирани символи не може да превишава "+ maxSelectedTextWidth +".";
    var TnxMessage = TnxMessage || "Благодаря Ви за съобщението! Администраторът в най-кратки срокове ще внесе поправката на страницата на сайта.";
    var copyRight = "<center style=\"background-color:#ffffff;\"><a href=\"http://www.editor.bg/\" target=\"_blank\" style=\"color:blue\">Ако желаете такава услуга за Вашият сайт безплатно, кликнете тук!</a></center>";


    var charset = document.charset || document.characterSet;

    var encodings = new Array ();
    encodings ['windows-1251'] = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯїЇєіІґҐўЎёЁЄ'.split('');
    encodings ['koi8-u'] = 'ЮАБЦДЕёФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪюабцдеЁфгхийклмнопярстужвьызшэщчъїЇєЁІЄҐўЎёЁЄ'.split('');
    encodings ['koi8-r'] = 'ЮАБЦДЕЈФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪюабцдеЁфгхийклмнопярстужвьызшэщчъїЇєЁІґҐўЎЈЁЄ'.split('');
    encodings ['iso-8859-5'] = 'рстуфхИцчшщъыьэюярстуфхцчшщъыьэюяРСТУФХёЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопПїКГВДµІ±Иёє'.split('');
    encodings ['gb2312'] = ['%A7%D1','%A7%D2','%A7%D3','%A7%D4','%A7%D5','%A7%D6','%A7%D7','%A7%D8','%A7%D9','%A7%DA', '%A7%DB','%A7%DC','%A7%DD','%A7%DE','%A7%DF','%A7%E0','%A7%E1','%A7%E2','%A7%E3','%A7%E4','%A7%E5','%A7%E6','%A7%E7','%A7%E8','%A7%E9','%A7%EA', '%A7%EB','%A7%EC','%A7%ED','%A7%EE','%A7%EF','%A7%F0','%A7%F1','%A7%A1','%A7%A2','%A7%A3','%A7%A4','%A7%A5','%A7%A6','%A7','%A7','%A7%A8','%A7%A9', '%A7%AA','%A7%AB','%A7%AC','%A7%AD','%A7%AE','%A7%AF','%A7%B0','%A7%B1','%A7%B2','%A7%B3','%A7%B4','%A7%B5','%A7%B6','%A7%B7','%A7%B8','%A7%B9', '%A7%BA','%A7%BB','%A7%BC','%A7%BD','%A7%BE','%A7%BF','%A7%C0','%A7%C1'];
    encodings ['utf-8'] = ['%D0%B0','%D0%B1','%D0%B2','%D0%B3','%D0%B4','%D0%B5', '%D1%91','%D0%B6','%D0%B7','%D0%B8','%D0%B9','%D0%BA','%D0%BB','%D0%BC', '%D0%BD','%D0%BE','%D0%BF','%D1%80','%D1%81','%D1%82','%D1%83','%D1%84', '%D1%85','%D1%86','%D1%87','%D1%88','%D1%89','%D1%8A','%D1%8B','%D1%8C', '%D1%8D','%D1%8E','%D1%8F','%D0%90','%D0%91','%D0%92','%D0%93','%D0%94', '%D0%95','%D0%81','%D0%96','%D0%97','%D0%98','%D0%99','%D0%9A','%D0%9B', '%D0%9C','%D0%9D','%D0%9E','%D0%9F','%D0%A0','%D0%A1','%D0%A2','%D0%A3', '%D0%A4','%D0%A5','%D0%A6','%D0%A7','%D0%A8','%D0%A9','%D0%AA','%D0%AB', '%D0%AC','%D0%AD','%D0%AE','%D0%AF','%D1%97','%D0%87','%D1%94','%D1%96', '%D0%86','%D2%91','%D2%90','%D1%9E','%D0%8E','%D1%91','%D0%81','%D0%84'];


    
    selectedTextFalseAlert = Decode (selectedTextFalseAlert, 'utf-8', charset.toLowerCase() );
    TnxMessage = Decode (TnxMessage, 'utf-8', charset.toLowerCase() );
    copyRight = Decode (copyRight, 'utf-8', charset.toLowerCase() );



    for(var i=0; i < encodings ['utf-8'].length; i++){
        encodings ['utf-8'][i] = unescape (encodings ['utf-8'][i])
        encodings ['gb2312'][i] = unescape (encodings ['gb2312'][i])
    }

    function dcTmp(X,from,into){
        for(var i=0;i<encodings ['windows-1251'].length;i++){
            if(X==from[i])return into[i]
        }
        return X
    }

    function Decode (txt, encFrom, encTo) {
      var aus = encodings [encFrom]; //eval(F.aus.options[F.aus.selectedIndex].value)
      var zu  = encodings [encTo];//eval(F.zu.options[F.zu.selectedIndex].value)

      if(''!=txt){
        if(-1<txt.indexOf(unescape('%D0')) || -1<txt.indexOf(unescape('%A7'))){
            for(var i=0;i<utf8.length;i++){
                var reg=eval('/'+aus[i]+'/g')
                txt=txt.replace(reg,zu[i])
                }
            }
        else{
        txt=txt.split('')
        for(var i=0;i<txt.length;i++){
            txt[i]=dcTmp(txt[i],aus,zu)
            }
        txt=txt.join('')
        }

            return txt;
        }
      else alert('Error while encoding!')
    }



    var gecko;
    var selectedText;
    var popWindowId = "PopWindow";
    var serviceURL = "http://editor.bg/server/orfoServer.php";
    var wasAdd = false;

    var isDOM = document.getElementById //DOM1 browser (MSIE 5+, Netscape 6, Opera 5+)
    var isOpera = isOpera5 = window.opera && isDOM //Opera 5+
    var isMSIE = document.all && document.all.item && !isOpera //Microsoft Internet Explorer 4+
    var isNetscape4 = document.layers //Netscape 4.*
    var isMozilla = isDOM && navigator.appName=="Netscape" //Mozilla шыш Netscape 6.*
    
    addEvent (window, 'load',  keyPressInit);



function addEvent (element, eventType, functionName)
{
    if (element.addEventListener) {
        element.addEventListener(eventType, functionName, false);
        return true;
    } else if (element.attachEvent) {
        var r = element.attachEvent('on' + eventType, functionName);
        return r;
    } else {
        element['on' + eventType] = functionName;
    }
}


function keyPressInit ()
{
    if (document.addEventListener)
    {
        document.addEventListener("keypress",
            function(e){keyAction(e)},true);
        if (navigator.appName == "Microsoft Internet Explorer") return;
        document.addEventListener("keydown", function(e){keyAction(e)}, true);
        gecko = true;
    } else if (document.attachEvent)
        document.attachEvent("onkeydown", keyAction);
}


function keyAction (e)
{
    if (!( ((e.shiftKey == true) && (pr_shift == true)) || ((e.altKey == true) && (pr_alt == true)) || ((e.ctrlKey == true) && (pr_ctrl == true)) )) return;
    var Key = e.keyCode;
    if (Key == 0) Key = e.charCode;
    if (Key == 13) {   
        if (!gecko && Key>64 && Key<91) Key += 32;
        GetSelectedText();
    }
}


function GetSelectedText ()
{
    var text = "";
    var selection = null;
    if (document.getSelection) {
        text = document.getSelection();
    } else {
        selection = document.selection;
    }
    if (selection) {
        var r = selection.createRange();
        if (!r) return null;
        text = r.text;
    }
    if (text) {
        text = text +"";
        if (text.length <= maxSelectedTextWidth) {
            selectedText = text;
            OpenPop ();
        } else {
            alert (selectedTextFalseAlert);
            return false;
        }
    }
}

function ClosePop ()
{
    var obj = document.getElementById (popWindowId);
    if (obj) {
        selectedText = '';
        obj.style.display = "none";
    }
}


function OpenPop ()
{
    var obj = document.getElementById (popWindowId);
    if (!obj) {
        var body = document.getElementsByTagName("body").item(0);
        var div = document.createElement("div");
        
        div.setAttribute("id", popWindowId);
        div.setAttribute("style", "position: absolute; display: block; width: 365px; height: 330px; z-index:20;");

        div.innerHTML = ''
                 + '  <fieldset style="padding: 10px; background-color:#ffffff;"><legend style="background-color:blue; color:white; font-weight:bold">'+ Decode ('Съобщете за грешка', 'utf-8', charset.toLowerCase() ) +'</legend>'
                 + '    '+ Decode ('Текст на грешката', 'utf-8', charset.toLowerCase() ) +':<br/>'
                 + '    <textarea cols="40" rows="3" id="PopWindowMistake" style="width:100%;"></textarea><br/>'
                 + '    '+ Decode ('Вашият вариант', 'utf-8', charset.toLowerCase() ) +':<br/>'
                 + '    <textarea cols="40" rows="3" id="PopWindowCorrect" style="width:100%;"></textarea><br/>'
                 + '    '+ Decode ('Коментар (не е задължително)', 'utf-8', charset.toLowerCase() ) +':<br/>'
                 + '    <textarea cols="40" rows="3" id="PopWindowComment" style="width:100%;"></textarea><br/><br/>'
                 + '    <input type="button" value="'+ Decode ('Изпрати', 'utf-8', charset.toLowerCase() ) +'" onclick="javascript:SendMistake ()" />'
                 + '    <input type="button" value="'+ Decode ('Затвори', 'utf-8', charset.toLowerCase() ) +'" onclick="javascript:ClosePop ()" />'
                 + '  </fieldset>';

        body.appendChild (div);
        obj = document.getElementById (popWindowId);    
    }


        var topSum=50;
        var topSum1=50;
        var leftSum=50;
        scrollTop = (parseInt(document.documentElement.scrollTop) > parseInt (document.body.scrollTop)) ? parseInt(document.documentElement.scrollTop) : parseInt (document.body.scrollTop);
        topSum = scrollTop + 50;
        leftSum = parseInt ((document.body.clientWidth/2)-(obj.style.width.substr (-0,3)/2));
        if (topSum<50) {
            topSum=50;
        }
        if (leftSum<50) {
            leftSum=50;
        }
        obj.style.top=topSum+'px';
        obj.style.left=leftSum+'px';
        if (isMozilla) obj.style.height += obj.style.height + 20;
        obj.style.display="block";

        var tmpObj = document.getElementById ("PopWindowMistake");
        if (tmpObj) tmpObj.value = selectedText;
        tmpObj = document.getElementById ("PopWindowCorrect");
        if (tmpObj) tmpObj.value = selectedText;

        if (!wasAdd) {
            obj.innerHTML = obj.innerHTML + copyRight;
            wasAdd = true;
        }

}


function SendMistake () {
    var mistake = document.getElementById ('PopWindowMistake').value;
    var correct = document.getElementById ('PopWindowCorrect').value;
    var comment = document.getElementById ('PopWindowComment').value;

    if (mistake && correct) {
        var url = serviceURL +"?mistake="+ encodeURIComponent(mistake) +"&correct="+ encodeURIComponent(correct) +"&comment="+ encodeURIComponent(comment) +"&email="+ encodeURIComponent(adminEmail) +"&from="+ encodeURIComponent(window.location) +"&tnxMsg="+ encodeURIComponent(TnxMessage);
        bObj = new JSONscriptRequest(url);
        bObj.buildScriptTag(); 
 
        ClosePop ();
        
        bObj.addScriptTag();
        bObj.removeScriptTag();
    }
}


// JSONscriptRequest -- a simple class for making HTTP requests
// Author: Jason Levitt
// Date: December 7th, 2005
function JSONscriptRequest(fullUrl) {
    this.fullUrl = fullUrl; 
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    this.headLoc = document.getElementsByTagName("head").item(0);
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}

JSONscriptRequest.scriptCounter = 1;

JSONscriptRequest.prototype.buildScriptTag = function () {
    this.scriptObj = document.createElement("script");
    
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
JSONscriptRequest.prototype.removeScriptTag = function () {
    this.headLoc.removeChild(this.scriptObj);  
}

JSONscriptRequest.prototype.addScriptTag = function () {
    this.headLoc.appendChild(this.scriptObj);
}