/**
Latin to Cyrillic Convertor version 3
Copyright (C) 2002 Petko Yotov http://5ko.free.fr/

Тази програма е "Свободен софтуер", автор Петко Йотов © 1999-2003.

Това е свободна програма; можете да я разпространявате и/или
променяте при условията на GNU GPL лиценза, публикуван от
Фондацията за свободни програми: или версия 2,
или (по Ваш избор) някоя следваща версия.

Тази програма е създадена с надеждата, че ще бъде полезна,
но БЕЗ НИКАКВА ГАРАНЦИЯ ЗА ТОВА, без дори косвена гаранция
за ПРИГОДНОСТ ЗА ОПРЕДЕЛЕНА ЦЕЛ. Вижте GNU GPL лиценза за
повече подробности.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

//пътят до скрипта и файла nastroiki3.html спрямо вашата страница
path2js = "http://www.5eg.net/board/buditel/";
// може да е относителен, "javascripts/cyr/", "../scripts/cyr/", или
// абсолютен, "/scripts/"; завършва с "/"; или празно, ако е в същата.
// Ако викате скрипта от различни страници, дайте абсолютен път.


dni = 60; //колко се запазва cookie-то


// ограничители за латиница - ако имате форум, изберете подходящите
ogra_original = "[]";


ogra_izbor = true; // възможност за промяна в "nastroiki3.html"
// ако имате форум, може да сложите false.


razdelitel_original = "'";//разделител s'hoden = сходен, а не шоден


//
link_na_kirilica = 'На кирилица';
link_na_latinica = 'На латиница';
link_nastroyki = 'Настройки';
link_pomosht = 'Помощ';
link_separator = "&nbsp;";
link_class = "lang";

button_na_kirilica = 'На кирилица';
button_na_latinica = 'На латиница';
button_nastroyki = 'Настройки';
button_pomosht = 'Помощ';
button_separator = "<br>\n";
button_class = "lang";


// Същинският скрипт



// ***  НЕ ПРОМЕНЯЙТЕ  ПО-НАДОЛУ, ОСВЕН АКО ЗНАЕТЕ КАКВО ПРАВИТЕ! ***
// ***  NE PROMENIAYTE PO-NADOLU, OSVEN AKO ZNAETE KAKVO PRAVITE! ***
azb_orig = "a.b.v.g.d.e.j.z.i.ii.k.l.m.n.o.p.r.s.t.u.f.h.c.4.6.6t.y.x.ju.q.."
azbuka_original = azb_orig.split(".");
bez_promiana = "...............................";


azbuka = new Array();
azb_frm = new Array();



function initiate()
{
// проверка дали има промени в Кукито

   tmp_c = getCookie("promeni");
   tmp = (tmp_c.length>0)? tmp_c : bez_promiana;
   var promenen = tmp.split(".");
   tips = "&#x0a;";
   azb = "абвгдежзийклмнопрстуфхцчшщъьюяыэАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЮЯЫЭ";

   for(i=0; i<azbuka_original.length; i++)
   {
      azbuka[i] = (promenen[i].length>0)? promenen[i] : azbuka_original[i];
      tips += "" + azb.charAt(i) + "=" + azbuka[i];
      tips += (i % 5 != 4) ? "&#x09;" : "&#x0a;";//&lt;br&gt; "";

      azb_frm[i] = azbuka[i];
      //eval("document.def.bukva_" + i + ".value = \"" + azbuka[i] + "\";");

   }
   razd = getCookie("rz");
   razdelitel = (razd.length>0)? razd : razdelitel_original;
   //document.def.razdelitel.value = razdelitel;
	razdRegExpSave = ("^|*()[]{}.-+?$/\\".indexOf(razdelitel)<0)?
		razdelitel : "\\" + razdelitel;



   ogra = getCookie("og");
   ogranichiteli = (ogra.length>0 && ogra_izbor)? ogra : ogra_original;
   og1 = ogranichiteli.charAt(0);
   og2 = ogranichiteli.charAt(1);

   tableau = new Array();
   cyr = new Array();
   azblen = azbuka.length;

   for(i=0; i<azblen; i++)
   {	cyr[i] = azb.charAt(i);
      tableau[i] = azbuka[i].length;
   }

   quicksort(0, azblen-1);
}


// Функции
function prevod(text, to_lat)
{
	if(! to_lat) to_lat = 0;
   var res = "";

   if(text.indexOf(og1) == -1)
   {  res = bash_prevod(text, to_lat);
   }

   else
   {
      var nachasti = text.split(og2);

      if(og1 == og2)
      {
         for(var i=0; i<nachasti.length; i++)
         {
            if(nachasti[i].length) res += "" + bash_prevod(nachasti[i], to_lat)

            i++;
            if(i<nachasti.length) res += "" +  og2 + nachasti[i] + og2 ;
         }

      }
      else
      {
         for(var i=0; i<nachasti.length; i++)
         {
            var c_l = nachasti[i].split(og1);
            if (c_l[0].length) res += "" + bash_prevod(c_l[0], to_lat);
            if (c_l[1] && c_l[1].length) res += og1 +  c_l[1] + og2;
         }
      }
   }
   zapisvane();

   return res;
}

function bash_prevod(text, to_lat)
{

	for(var i=azbuka.length-1; i>=0 ; i--)
	//отзад напред - първо sht, после sh.
	{	if(azbuka[i].length > 0 && azbuka[i] != " ")
		{
			var search_for = (to_lat)? cyr[i] : azbuka[i];
			var replace_with = (to_lat)? azbuka[i] : cyr[i];

         p = new RegExp(search_for, "g");
			text = text.replace(  p, replace_with );
         p = new RegExp(search_for, "gi");// :))
			text = text.replace(  p, replace_with.toUpperCase() );
		}
	}
	if(razdelitel.length > 0 && razdelitel != " ")
	{	p = new RegExp(razdRegExpSave, "g");
		text = text.replace(p, "");
	}
	return text;
}

// 2 funkcii ot K&R :))
function permute(a, b)
{	var c = tableau[a];
	var d = azbuka[a];
	var e = cyr[a];

	tableau[a] = tableau[b];
	azbuka[a] = azbuka[b];
	cyr[a] = cyr[b];

	tableau[b] = c;
	azbuka[b] = d;
	cyr[b] = e;
}

function quicksort(gauche, droite)
{// из "K&R quicksort" - сортира всички букви според
// дължината на латинските еквиваленти.
// Преводът трябва да почне от по-дългите.
 if (gauche >= droite) return;
  permute(gauche, Math.floor((gauche + droite) / 2));
  dernier = gauche;
  for (i=gauche+1; i <=droite; i++)
   if (tableau[i] < tableau[gauche]) permute(++dernier, i);
  permute(gauche, dernier);
  quicksort(gauche, dernier-1);
  quicksort(dernier+1, droite);
}

function zapisvane()//за още (60) дни, само ако посетителят направи превод
{	if(tmp_c) setCookie("promeni", tmp_c, dni);
	if(razd) setCookie("rz", razd, dni);
	if(ogra) setCookie("og", ogra, dni);
}

function setCookie(ime, stoinost, dni)
{	if(dni == null)trainost = "";
	else
	{	EXPIR = new Date();
		EXPIR.setTime(EXPIR.getTime() + (1000*60*60*24*dni));
		trainost = "; expires=" + EXPIR.toGMTString();
	}
	document.cookie = "" + ime + "=" + escape(stoinost) + trainost;
}

function getCookie(ime)
{
   var nachalo = document.cookie.indexOf(ime + "=");

   if (nachalo == -1) return "";

   // else
   var ind1 = nachalo + 1 + ime.length;

	ind2 = document.cookie.indexOf(";", ind1);
	if(ind2 == -1)ind2 = document.cookie.length;

   return unescape(document.cookie.substring(ind1, ind2));
}

function nastroiki()
{
   var nastr = window.open(path2js + "buditel-settings.html","nastr", "width=600,height=395,scrollbars");
   nastr.focus();
}
function pomosht()
{
   var nastr = window.open(path2js + "buditel-help.html","nastr", "width=600,height=395,scrollbars");
   nastr.focus();
}

function textlinx()
{	document.write('<a href="#" id="langLink" title="Избиране на клавиатурна подредба" onclick="toggleLang(); return false;" class="'+ link_class +'"></a>');
   var html = '<a class="'+ link_class +'" href="javascript:void(0);" onClick="with(document){';

   for(var j=0; j<textlinx.arguments.length; j++)
   {
      html += textlinx.arguments[j] + '.value=prevod(';
      html += textlinx.arguments[j] + '.value, 0);'
   }
   html += '}" title="Превежда текста от Latinica => Кирилица:  \n' + tips + '">'+ link_na_kirilica +'</a>';
   html += '<a class="'+ link_class +'" href="javascript:void(0);" onClick="with(document){';

   for(var j=0; j<textlinx.arguments.length; j++)
   {
      html += textlinx.arguments[j] + '.value=prevod(';
      html += textlinx.arguments[j] + '.value, 1);'
   }
   html += '}" title="Превежда текста от Кирилица => Latinica : \n' + tips + '">'+ link_na_latinica +'</a>';
   html += '<a class="'+ link_class +'" href="javascript:nastroiki();" title="Настройте буквите, така че да са ви удобни">'+ link_nastroyki +'</a>';
   html += '<a class="'+ link_class +'" href="javascript:pomosht();" title="Информация за програмата" style="cursor: help;">'+ link_pomosht +'</a>';
   document.writeln(html);
}

function buttons()
{
   var html = '<input class="'+ button_class +'" type="button" onClick="with(document){';

   for(var j=0; j<buttons.arguments.length; j++)
   {
      html += buttons.arguments[j] + '.value=prevod(';
      html += buttons.arguments[j] + '.value, 0);'
   }
   html += '}" title="Превежда текста от Latinica => Кирилица: \n' + tips + '" value="'+ button_na_kirilica +'">'+ button_separator;
   html += '<input class="'+ button_class +'" type="button" onClick="with(document){';

   for(var j=0; j<buttons.arguments.length; j++)
   {
      html += buttons.arguments[j] + '.value=prevod(';
      html += buttons.arguments[j] + '.value, 1);'
   }
   html += '}" title="Превежда текста от Кирилица => Latinica : \n' + tips + '" value="'+ button_na_latinica +'">'+ button_separator;
   html += '<input class="'+ button_class +'" type="button" onClick="nastroiki();" title="Настройте буквите, така че да са ви удобни" value="' + button_pomosht + '" style="cursor: help;">';
   html += '<input class="'+ button_class +'" type="button" onClick="pomosht();" title="Информация за програмата" value="' + button_pomosht + '" style="cursor: help;">';

   document.writeln(html);
}
function whattime()
{// тест за скорост
   var sega = new Date();
   return sega.getTime();
}

initiate();





