/*
////////////////////////////////////////////////////////////////////////
// WikiEdit                                                           //
// v. 2.15                                                            //
// supported: MZ1.4+, MSIE5+                                          //
//                                                                    //
// (c) Roman "Kukutz" Ivanov <thingol@mail.ru>, 2003-2004             //
//   based on AutoIndent for textarea                                 //
//   (c) Roman "Kukutz" Ivanov, Evgeny Nedelko, 2003                  //
// Many thanks to Alexander Babaev, Sergey Kruglov and Evgeny Nedelko //
// http://wackowiki.com/WikiEdit                                      //
//                                                                    //
////////////////////////////////////////////////////////////////////////

For license see LICENSE.TXT
*/

var WikiEdit = function(){
 this.mark = "##inspoint##";
 this.begin = "##startpoint##";
 this.rbegin = new RegExp(this.begin);
 this.end = "##endpoint##";
 this.rend = new RegExp(this.end);
 this.rendb = new RegExp("^" + this.end);
 this.enabled = true;
 this.tab = false;
 this.enterpressed = false;
 this.undostack = new Array();
 this.buttons = new Array();
}

WikiEdit.prototype = new ProtoEdit();
WikiEdit.prototype.constructor = WikiEdit;

// initialisation
WikiEdit.prototype.init = function(id, name, nameClass, imgPath) {
 if (!(isMZ || isIE || isO8)) return;
 this.mzBugFixed=true;
 if (isMZ && navigator.userAgent.substr(navigator.userAgent.indexOf("Gecko/")+6,4)=="2003" ) {
  this.mzBugFixed=(navigator.userAgent.substr(navigator.userAgent.indexOf("Gecko/")+6,8)>20030510);
  mzOld=(navigator.userAgent.substr(navigator.userAgent.indexOf("Gecko/")+6,8)<20030110);
  if (mzOld) this.MZ=false;
  else this.MZ=true;
 }
 if (isMZ && navigator.userAgent.substr(navigator.userAgent.indexOf("Gecko/")+6,4)=="2002" ) this.MZ=false;
 if (!(this.MZ || isIE || isO8)) return;

 this._init(id);
// if (!this.area.id) this.area.id = "area_"+String(Math.floor(Math.random()*10000));

 this.imagesPath = (imgPath?imgPath:"images/edit/");
 this.editorName = name;
 this.editorNameClass = nameClass;

 this.actionName = "document.getElementById('" + this.id + "')._owner.insTag";

 if (isMZ || isO8)
 {
 try {
  this.undotext = this.area.value;
  this.undosels = this.area.selectionStart;
  this.undosele = this.area.selectionEnd;
 } catch(e){};
 }
 if (isIE)
 {
  this.area.addBehavior(this.imagesPath+"sel.htc");
 }
 
 this.colors = new Array();
 for (i=0; i < 4; i++) {
  this.colors[i] = new Array();
 }
  
 this.colors[0][0] = 'Black';
 this.colors[1][0] = 'Maroon';
 this.colors[2][0] = 'Green';
 this.colors[3][0] = 'Navy';
 this.colors[0][1] = 'Silver';
 this.colors[1][1] = 'Red';
 this.colors[2][1] = 'Lime';
 this.colors[3][1] = 'Blue';
 this.colors[0][2] = 'Gray'; 
 this.colors[1][2] = 'Purple';
 this.colors[2][2] = 'Olive';
 this.colors[3][2] = 'Teal';
 this.colors[0][3] = 'White';
 this.colors[1][3] = 'Fuchsia';
 this.colors[2][3] = 'Yellow';
 this.colors[3][3] = 'Aqua';

 this.codenames = new Array();
 this.codenames[0] = 'text';
 this.codenames[1] = 'php';
 this.codenames[2] = 'perl';
 this.codenames[3] = 'java';
 this.codenames[4] = 'html';
 this.codenames[5] = 'xml';
 this.codenames[6] = 'sql';
 this.codenames[7] = 'c++';
 this.codenames[8] = 'pascal';

 this.actionName = "document.getElementById('" + this.id + "')._owner.insTag";

 this.addButton("h1","Заголовок 1","'[h1]','[/h1]',0,1,0");
 this.addButton("h2","Заголовок 2","'[h2]','[/h2]',0,1,0");
 this.addButton("h3","Заголовок 3","'[h3]','[/h3]',0,1,0");

 this.addButton("bold","Жирный","'[b]','[/b]',2,0,0");
 this.addButton("italic","Курсив","'[i]','[/i]',2,0,0");
 this.addButton("underline","Подчеркнутый","'[u]','[/u]',2,0,0");
 this.addButton("s","Зачеркнутый","'[s]','[/s]',2,0,0");

 this.addButton("left","Влево","'[left]','[/left]',0,1,0");
 this.addButton("center","По центру","'[center]','[/center]',0,1,0");
 this.addButton("right","Вправо","'[right]','[/right]',0,1,0"); 

 this.addButton("color","Цвет","'color_"+this.id+"'","document.getElementById('" + this.id + "')._owner.colorList");
 this.addButton("size","Размер","'size_"+this.id+"'","document.getElementById('" + this.id + "')._owner.sizeList");

 this.addButton("hr","Линия","'','\\n[hr]\\n',2"); 
 this.addButton("list","Список","","document.getElementById('" + this.id + "')._owner.createList");
 this.addButton("listnum","Нумерованный список","","document.getElementById('" + this.id + "')._owner.createListNum");
 this.addButton("quote","Цитата","","document.getElementById('" + this.id + "')._owner.createQuote");
 this.addButton("code","Код","'code_"+this.id+"'","document.getElementById('" + this.id + "')._owner.codeList");

 this.addButton("link","Именованная ссылка","","document.getElementById('" + this.id + "')._owner.createLink");
 this.addButton("img","Ссылка на фото","'[img]','[/img]',2,0,0");
 this.addButton("image","Загрузить фото с компа","'image_"+this.id+"'","document.getElementById('" + this.id + "')._owner.uploadImage");

// this.addButton("createtable","Insert Table","'','\\n#|\\n|| | ||\\n|| | ||\\n|#\\n',2");

// this.addButton("help","Help & About","","document.getElementById('" + this.id + "')._owner.help");
/*
 this.addButton("customhtml",'<td><div style="font:12px Arial;text-decoration:underline; padding:4px;" id="hilfe_' + this.id + '" onmouseover=\'this.className="btn-hover";\' '
            + 'onmouseout=\'this.className="btn-";\' class="btn-" '
            + 'onclick="this.className=\'btn-pressed\';window.open(\'http://wackowiki.com/WackoDocumentation/WackoFormatting\');" '
            + ' title="Help on Wiki-formatting">Help</a>'
            + '</div></td>');
 
*/
 try {
  var toolbar = document.createElement("div");
  toolbar.id = "tb_"+this.id;
  this.area.parentNode.insertBefore(toolbar, this.area);
  toolbar = document.getElementById("tb_"+this.id);
  toolbar.innerHTML = this.createToolbar(this.id);
 // this.area.addEventListener("focus", this.hideDDmenu, false);	
 } catch(e){};
}

// internal functions ----------------------------------------------------
WikiEdit.prototype._LSum = function (Tag, Text, Skip)
{
 if (Skip)
 {
  var bb = new RegExp("^([ ]*)([*][*])(.*)$");
  q = Text.match(bb);
  if (q!=null)
  {
   Text = q[1]+Tag+q[2]+q[3];
   return Text;
  }
  var w = new RegExp("^([ ]*)(([*]|([1-9][0-9]*|[a-zA-Z])([.]|[)]))( |))(.*)$");
  q = Text.match(w);
  if (q!=null)
  {
   Text = q[1]+q[2]+Tag+q[7];
   return Text;
  }
 }
 var w  = new RegExp("^([ ]*)(.*)$");
 q = Text.match(w);
 Text = q[1]+Tag+q[2];
 return Text;
}

WikiEdit.prototype._RSum = function (Text, Tag)
{
 var w  = new RegExp("^(.*)([ ]*)$");
 q = Text.match(w);
 Text = q[1]+Tag+q[2];
 return Text;
}

WikiEdit.prototype._TSum = function (Text, Tag, Tag2, Skip)
{
 var bb = new RegExp("^([ ]*)"+this.begin+"([ ]*)([*][*])(.*)$");
 q = Text.match(bb);
 if (q!=null)
 {
  Text = q[1]+this.begin+q[2]+Tag+q[3]+q[4];
 }
 else
 {
  var w = new RegExp("^([ ]*)"+this.begin+"([ ]*)(([*]|([1-9][0-9]*|[a-zA-Z])([.]|[)]))( |))(.*)$");
  q = Text.match(w);
  if (Skip && q!=null)
  {
   Text = q[1]+this.begin+q[2]+q[3]+Tag+q[8];
  }
  else
  {
   var w = new RegExp("^(.*)"+this.begin+"([ ]*)(.*)$");
   var q = Text.match(w);
   if (q!=null)
   {
    Text = q[1]+this.begin+q[2]+Tag+q[3];
   }
  }
 }
 var w = new RegExp("([ ]*)"+this.end+"(.*)$");
 var q = Text.match(w);
 if (q!=null)
 {
  var w = new RegExp("^(.*)"+this.end);
  var q1 = Text.match(w);
  if (q1!=null)
  {
   var s = q1[1];
   ch = s.substring(s.length-1, s.length);
   while (ch == " ") {
      s = s.substring(0, s.length-1);
      ch = s.substring(s.length-1, s.length);
   }
   Text = s+Tag2+q[1]+this.end+q[2];
  }
 }
 return Text;
}

WikiEdit.prototype.MarkUp = function (Tag, Text, Tag2, onNewLine, expand, strip)
{
 var skip = 0;
 if (expand == 0) skip = 1;
 var r = '';
 var fIn = false;
 var fOut = false;
 var add = 0;
 var f = false;
 var w = new RegExp("^  ( *)(([*]|([1-9][0-9]*|[a-zA-Z])([.]|[)]))( |))");
 if (!isO8) Text = Text.replace(new RegExp("\r", "g"), "");
 if (!isO8) var lines = Text.split('\n');
 else var lines = Text.split('\r\n');
 for(var i = 0; i < lines.length; i++) {
   if (this.rbegin.test(lines[i]))
     fIn = true;
   if (this.rendb.test(lines[i]))
     fIn = false;
   if (this.rend.test(lines[i]))
     fOut = true;
   if (this.rendb.test(lines[i+1])) {
     fOut = true;
     lines[i+1]=lines[i+1].replace(this.rend, "");
     lines[i]=lines[i]+this.end;
   }
   if (r != '')
     r += '\n';

  if (fIn && strip==1) {
    if (this.rbegin.test(lines[i]))
    {
     lines[i] = lines[i].replace(this.rbegin, "");
     f = true;
    } else f=false;
//  alert(lines[i].replace(new RegExp("\n","g"),"|").replace(new RegExp(" ","g"),"_"));
    lines[i] = lines[i].replace(w, "$1");
//  alert(lines[i].replace(new RegExp("\n","g"),"|").replace(new RegExp(" ","g"),"_"));
    if (f) lines[i] = this.begin+lines[i];
  }
/*
 fIn &&
  onNewLine==0 //добавляем таги.
  onNewLine==1 //добавляем таги, если первая строка
  onNewLine==2 //добавляем таги, если первая_и_последняя строка, иначе
   //добавляем первый таг, если первая либо добавляем последний, если последняя
 //иначе добавляем неизменный текст
*/
  if (fIn && (onNewLine==0 | (onNewLine==1 && add==0) | (onNewLine==2 && (add==0 || fOut)))) {
  //добавляем таги
    if (expand==1) {
      l = lines[i];
      if (add==0) l = this._LSum(Tag, l, skip);
      if (fOut)   l = this._RSum(l, Tag2);
      if (add!=0 && onNewLine!=2) l = this._LSum(Tag, l, skip);
      if (!fOut  && onNewLine!=2) l = this._RSum(l, Tag2);
      r += l;
    } else {
/*
  не экспанд. это значит, что
  если первая строка, то добавляем реплейсом первый и суммой второй
  если последняя, то добавляем суммой первый и реплейсом второй
  если первая и последняя, то оба реплейсом
  иначе суммой
*/
//    alert(lines[i].replace(new RegExp("\n","g"),"|").replace(new RegExp(" ","g"),"_"));
//    alert(lines[i+1].replace(new RegExp("\n","g"),"|").replace(new RegExp(" ","g"),"_"));
      l = this._TSum(lines[i], Tag, Tag2, skip);
      if (add!=0 && onNewLine!=2) l = this._LSum(Tag, l, skip);
      if (!fOut  && onNewLine!=2) l = this._RSum(l, Tag2);
      r += l;
    }
    add++;
  } else {
  //добавляем неизменный текст
    r += lines[i];
  }
  if (fOut)
   fIn = false;
 }
 return r;
}


WikiEdit.prototype.getDefines = function ()
{
  var t = this.area;

  text = t.value;
  if (!isO8) text = text.replace(/\r/g, "");
  this.ss = t.selectionStart;
  this.se = t.selectionEnd;
//	alert(this.ss+' '+this.se);
  this.sel1 = text.substr(0, this.ss);
  this.sel2 = text.substr(this.se);
  this.sel = text.substr(this.ss, this.se - this.ss);
  this.str = this.sel1+this.begin+this.sel+this.end+this.sel2;
  if (isMZ) 
  {
   this.scroll = t.scrollTop;
   this.undotext = t.value;
   this.undosels = t.selectionStart;
   this.undosele = t.selectionEnd;
  }

}

WikiEdit.prototype.setAreaContent = function (str)
{
  var t = this.area;
  q = str.match(new RegExp("((.|\n)*)"+this.begin));//?:
  l = q[1].length;//длина до тега
  if (isO8) l = l + q[1].split('\n').length - 1;

  q = str.match(new RegExp(this.begin+"((.|\n)*)"+this.end));
	z = q[1].match(new RegExp("(^\\[([^\\].])*\\])((.|\n)*)((\\[([^\\].])*\\])$)"));

  if (z) //если парный тег
  {	
		l = l + z[1].length; //длина до тега + длина тега
		l1 = z[3].length; //длина тела
		if (isO8) l1 = l1 + z[3].split('\n').length - 1; 
  } else {
   	l1 = q[1].length; //длина тела вместе с тегом
   	if (isO8) l1 = l1 + q[1].split('\n').length - 1; 
	}  
  str = str.replace(this.rbegin, "");
  str = str.replace(this.rend, "");
  t.value = str;
  t.setSelectionRange(l, l + l1);
  if (isMZ) t.scrollTop = this.scroll;
}

WikiEdit.prototype.insTag = function (Tag, Tag2, onNewLine, expand, strip)
{
/*
onNewLine:
0 - add tags on every line inside selection
1 - add tags only on the first line of selection
2 - add tags before and after selection
//3 - add tags only if there's one line -- not implemented

expand:
0 - add tags on selection
1 - add tags on full line(s)
*/
  if (onNewLine == null) onNewLine = 0;
  if (expand == null) expand = 0;
  if (strip == null) strip = 0;

  var t = this.area;
  t.focus();

  this.getDefines();

  //alert(Tag + " | " + Tag2 + " | " + onNewLine + " | " + expand + " | " + strip);
  str = this.MarkUp(Tag, this.str, Tag2, onNewLine, expand, strip);
  this.setAreaContent(str);
  return true;
}

WikiEdit.prototype.createList = function (isAlt)
{
  res = this.insTag("[*]", "", 0, 0, 0);
  res = this.insTag("[list]","[/list]", 2,0,0);
  return true;
}

WikiEdit.prototype.createListNum = function (isAlt)
{
  res = this.insTag("[*]", "", 0, 0, 0);
  res = this.insTag("[list=1]","[/list]", 2,0,0);
  return true;
}

WikiEdit.prototype.createLink = function (isAlt)
{
  var t = this.area;
  t.focus();

  this.getDefines();

  var n = new RegExp("\n");
  if (!n.test(this.sel)) {
    if (!isAlt) {
     lnk = prompt("Адрес:", this.sel);
     if (lnk==null) lnk = this.sel;
     sl = prompt("Текст для ссылки:", this.sel);
     if (sl==null) sl = "";
    };
    str = this.sel1+"[a url="+lnk+"]"+sl+"[/a]"+this.sel2;
    t.value = str;
    t.setSelectionRange(this.sel1.length, str.length-this.sel2.length);
    return true;
  }
  return false;
}

WikiEdit.prototype.createQuote = function (isAlt)
{
	author = prompt("Заголовок цитаты:", "");
	if (author == null) {
		return true;
	}	
	if (author == "") {
  		alert("Не надо оставлять пустым заголовок цитаты");
		return true;
	}
	if (author.length > 25 ) {
		alert("Давай ка покороче заголовок. Не больше 25 букв будет норм");
		return true;
	}	
	res = this.insTag("[quote="+'\"'+author+'\"'+"]", "[/quote]",2, 0, 0);
	return true;
}

WikiEdit.prototype.hideDDmenu = function ()
{
	var div = document.getElementById('dropdown_menu_'+this.id);
	div.style.display = 'none';
  return false;
}



// Определение координат и размеров элемента
WikiEdit.prototype.getCoords = function (element) {
    var left = element.offsetLeft;
    var top = element.offsetTop;
    for (var parent = element.offsetParent; parent; parent = parent.offsetParent) {
        left += parent.offsetLeft - parent.scrollLeft;
        top += parent.offsetTop - parent.scrollTop
    }
    return {    	left: left,
    	top: top,
    	width: element.offsetWidth,
    	height: element.offsetHeight
    };
}


// Показывает палитру выбора цвета
WikiEdit.prototype.colorList = function (id) {  var div = document.getElementById('dropdown_menu_'+this.id);
	if ('none' != div.style.display) {
        div.style.display = 'none';
        return false;
    }
    var coords = this.getCoords(document.getElementById(id));
    div.style.left = coords['left'] + 'px';
    div.style.top = coords['top'] + coords['height'] + 'px';
    var html = '<table border="0" cellpadding="0" cellspacing="1">';
    for (var i = 0; this.colors[i]; ++i) {
        html += '<tr>';
        for (var j = 0; this.colors[i][j]; ++j) {            html += '<td height="20" width="20" bgcolor="' + this.colors[i][j]
                + '" onclick="'+this.actionName+'(\'[color='+this.colors[i][j]+']\', \'[/color]\', 2,0,0)">' 
                + '<img alt="' + this.colors[i][j]
                + '"  src="'+this.imagesPath+'pixel.gif" height="20" width="20" class="opt_color" /></td>';
        }
        html += '</tr>';
    }
    html += '</table>';
    div.innerHTML = html;
    div.style.display = '';
    return false;
}
WikiEdit.prototype.sizeList = function (id) {  var div = document.getElementById('dropdown_menu_'+this.id);
	if ('none' != div.style.display) {
        div.style.display = 'none';
        return false;
    }
    var coords = this.getCoords(document.getElementById(id));
    div.style.left = coords['left'] + 'px';
    div.style.top = coords['top'] + coords['height'] + 'px';
    var html = '';
    for (var i = 1; i <= 7; ++i) {
        html += '<font size="' +i+ '" style="cursor: pointer;" onclick="'+this.actionName+'(\'[size='+i+']\', \'[/size]\', 2,0,0)">Размер&nbsp;'+ i + '</font><br />';
    }
    div.innerHTML = html;
    div.style.display = '';
    return false;
}


WikiEdit.prototype.codeList = function (id) {  var div = document.getElementById('dropdown_menu_'+this.id);
	if ('none' != div.style.display) {
        div.style.display = 'none';
        return false;
    }
    var coords = this.getCoords(document.getElementById(id));
    div.style.left = coords['left'] + 'px';
    div.style.top = coords['top'] + coords['height'] + 'px';
    var html = '';
    for (var j = 0; this.codenames[j]; ++j) {    	html += '<div style="cursor: pointer;" onclick="'+this.actionName+'(\'[code='+this.codenames[j]+']\', \'[/code]\', 2,0,0)">'+this.codenames[j]+'</div>'; 
    }
    div.innerHTML = html;
    div.style.display = '';
    return false;
}

WikiEdit.prototype.uploadImage = function (id) {
  var div = document.getElementById('dropdown_menu_'+this.id);
	if ('none' != div.style.display) {
        div.style.display = 'none';
        return false;
    }
        var coords = this.getCoords(document.getElementById(id));
    div.style.left = coords['left'] - 270 + 'px';
    div.style.top = coords['top'] + coords['height'] + 'px';
    var html = '<iframe frameborder="0" id="u1" src="upload_img.php?tid='+this.id+'"></iframe>'
    div.innerHTML = html;
    div.style.display = '';
    return false;
}

WikiEdit.prototype.help = function ()
{
 s =  "    bbcode editor \n";
 s += "  Тут пока них нету   \n";

 alert(s);
}
