String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function show(id){
	if( document.getElementById(id).style.display==""){
		document.getElementById(id).style.display="none";
	}else{
		document.getElementById(id).style.display="";
	}
}

function TableShowMAIL(id,div1,div2){
	if( document.getElementById(id).style.display==""){
		document.getElementById(div2).style.display="";
		document.getElementById(div1).style.display="none";

		document.getElementById(id).style.display="none";
	}else{
		document.getElementById(div2).style.display="none";
		document.getElementById(div1).style.display="";

		document.getElementById(id).style.display="";
	}
}

function ToggleCuttedBlock(item)
{
	titleBlock = $(item);
	textBlock = $(item).parent().children('div.cuttedBlockText');
	textBlockVisible = $(textBlock).css('display') == 'none' ? true : false;
	textBlock.slideToggle(300);
	$(titleBlock).attr('class', textBlockVisible ? 'cuttedBlockTitleOpen' : 'cuttedBlockTitleClose');
}

// BBCode control.
function BBCode(textarea) { this.construct(textarea) }
BBCode.prototype = {
  VK_TAB:     9,
  VK_ENTER:   13,
  VK_PAGE_UP: 33,
  BRK_OP:     '[',
  BRK_CL:     ']',
  textarea:   null,
  stext:      '',
  quoter:     null,
  collapseAfterInsert: false,
  replaceOnInsert: false,

  // Create new BBCode control.
  construct: function(textarea) {
    var th = this;
    this.textarea = textarea
    this.tags     = new Object();

  },

  // Insert poster name or poster quotes to the text.
  onclickPoster: function(name) {
    var sel = this.getSelection()[0];
    if (sel) {
      this.quoter = name;
      this.quoterText = sel;
      this.insertTag('_quoter');
    } else {
      this.insertAtCursor("[b][u]" + name + '[/u][/b]');
    }
    return false;
  },

  // For stupid Opera - save selection before mouseover the button.
  refreshSelection: function(get) {
    if (get) this.stext = this.getSelection()[0];
    else this.stext = '';
  },

  // Return current selection and range (if exists).
  // In Opera, this function must be called periodically (on mouse over,
  // for example), because on click stupid Opera breaks up the selection.
  getSelection: function() {
    var w = window;
    var text='', range;
    if (w.getSelection) {
      // Opera & Mozilla?
      text = w.getSelection();
    } else if (w.document.getSelection) {
      // the Navigator 4.0x code
      text = w.document.getSelection();
    } else if (w.document.selection && w.document.selection.createRange) {
      // the Internet Explorer 4.0x code
      range = w.document.selection.createRange();
      text = range.text;
    } else {
      return [null, null];
    }
    if (text == '') text = this.stext;
    text = ""+text;
    text = text.replace("/^\s+|\s+$/g", "");
    return [text, range];
  },

  // Insert string at cursor position of textarea.
  insertAtCursor: function(text) {
    // Focus is placed to textarea.
    var t = this.textarea;
    t.focus();
    // Insert the string.
    if (document.selection && document.selection.createRange) {
      var r = document.selection.createRange();
      if (!this.replaceOnInsert) r.collapse();
      r.text = text;
    } else if (t.setSelectionRange) {
      var start = this.replaceOnInsert? t.selectionStart : t.selectionEnd;
      var end   = t.selectionEnd;
      var sel1  = t.value.substr(0, start);
      var sel2  = t.value.substr(end);
      t.value   = sel1 + text + sel2;
      t.setSelectionRange(start+text.length, start+text.length);
    } else{
      t.value += text;
    }
    // For IE.
    setTimeout(function() { t.focus() }, 100);
  },

  // Surround piece of textarea text with tags.
  surround: function(open, close, fTrans) {
    var t = this.textarea;
    t.focus();
    if (!fTrans) fTrans = function(t) { return t; };

    var rt    = this.getSelection();
    var text  = rt[0];
    var range = rt[1];
    if (text == null) return false;

    var notEmpty = text != null && text != '';

    // Surround.
    if (range) {
      var notEmpty = text != null && text != '';
      var newText = open + fTrans(text) + (close? close : '');
      range.text = newText;
      range.collapse();
      if (text != '') {
        // Correction for stupid IE: \r for moveStart is 0 character.
        var delta = 0;
        for (var i=0; i<newText.length; i++) if (newText.charAt(i)=='\r') delta++;
        range.moveStart("character", -close.length-text.length-open.length+delta);
        range.moveEnd("character", -0);
      } else {
        range.moveEnd("character", -close.length);
      }
      if (!this.collapseAfterInsert) range.select();
    } else if (t.setSelectionRange) {
      var start = t.selectionStart;
      var end   = t.selectionEnd;
      var sel1  = t.value.substr(0, start);
      var sel2  = t.value.substr(end);
      var sel   = fTrans(t.value.substr(start, end-start));
      var inner = open + sel + close;
      t.value   = sel1 + inner + sel2;
      if (sel != '') {
        t.setSelectionRange(start, start+inner.length);
        notEmpty = true;
      } else {
        t.setSelectionRange(start+open.length, start+open.length);
        notEmpty = false;
      }
      if (this.collapseAfterInsert) t.setSelectionRange(start+inner.length, start+inner.length);
    } else {
      t.value += open + text + close;
    }
    this.collapseAfterInsert = false;
    return notEmpty;
  },

  // Internal function for cross-browser event cancellation.
  _cancelEvent: function(e) {
    if (e.preventDefault) e.preventDefault();
    if (e.stopPropagation) e.stopPropagation();
    return e.returnValue = false;
  },

   // Adds a BB tag to the list.
  addTag: function(id, open, close, key, ctrlKey, multiline) {
    if (!ctrlKey) ctrlKey = "ctrl";
    var tag = new Object();
    tag.id        = id;
    tag.open      = open;
    tag.close     = close;
    tag.key       = key;
    tag.ctrlKey   = ctrlKey;
    tag.multiline = multiline;
    tag.elt       = document.getElementById(id);
    this.tags[id] = tag;
    // Setup events.
    var elt = tag.elt;
    if (elt) {
      var th = this;
      if (!elt.type || elt.type.toUpperCase()=="BUTTON" ) {
        addEvent(elt, 'onclick', function() { th.insertTag(id); return false; });
      }
      if (elt.tagName && elt.tagName.toUpperCase()=="SELECT") {
        addEvent(elt, 'onchange', function() { th.insertTag(id); return false; });
      }
    } else {
      if (id && id.indexOf('_') != 0) return alert("addTag('"+id+"'): no such element in the form");
    }
  },

  // Inserts the tag with specified ID.
  insertTag: function(id) {
    // Find tag.
    var tag = this.tags[id];
    if (!tag) return alert("Unknown tag ID: "+id);

    // Open tag is generated by callback?
    var op = tag.open;
    if (typeof(tag.open) == "function") op = tag.open(tag.elt);
    var cl = tag.close!=null? tag.close : "/"+op;

    // Use "[" if needed.
    if (op.charAt(0) != this.BRK_OP) op = this.BRK_OP+op+this.BRK_CL;
    if (cl && cl.charAt(0) != this.BRK_OP) cl = this.BRK_OP+cl+this.BRK_CL;

    this.surround(op, cl, !tag.multiline? null : tag.multiline===true? this._prepareMultiline : tag.multiline);
  },

  _prepareMultiline: function(text) {
    text = text.replace(/\s+$/, '');
    text = text.replace(/^([ \t]*\r?\n)+/, '');
    if (text.indexOf("\n") >= 0) text = "\n" + text + "\n";
    return text;
  }

}

// Cross-browser addEventListener()/attachEvent() replacement.
function addEvent(elt, name, handler, atEnd) {
  name = name.replace(/^(on)?/, 'on');
  var prev = elt[name];
  var tmp = '__tmp';
  elt[name] = function(e) {
    if (!e) e = window.event;
    var result;
    if (!atEnd) {
      elt[tmp] = handler; result = elt[tmp](e); elt[tmp] = null; // delete() does not work in IE 5.0 (???!!!)
      if (result === false) return result;
    }
    if (prev) {
      elt[tmp] = prev; result = elt[tmp](e); elt[tmp] = null;
    }
    if (atEnd && result !== false) {
      elt[tmp] = handler; result = elt[tmp](e); elt[tmp] = null;
    }
    return result;
  }
  return handler;
}

// Emulation of innerText for Mozilla.
if (window.HTMLElement && window.HTMLElement.prototype.__defineSetter__) {
  HTMLElement.prototype.__defineSetter__("innerText", function (sText) {
     this.innerHTML = sText.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  });
  HTMLElement.prototype.__defineGetter__("innerText", function () {
     var r = this.ownerDocument.createRange();
     r.selectNodeContents(this);
     return r.toString();
  });
}


function ResizeAnswerArea(size)
{
	var area = window.document.getElementById("answerArea");
	aheight = parseInt(area.clientHeight);
	if ( isNaN(aheight) )
		aheight = 100;
	if ( aheight + size > 20 && aheight + size < 500 )
	{
		area.style.height = aheight + size + 'px';
	}
}

function InsertQuote(text, user)
{
	var area = window.document.getElementById("answerArea");
	bbcode.insertAtCursor("[quote "+user+"]"+text+"[/quote]");
	ResizeAnswerArea(40);
}

function InsertUrl(el)
{
	var text = '';
	var t = bbcode.textarea;
	if (t.setSelectionRange) {
		var start = t.selectionStart;
		var end   = t.selectionEnd;
		var sel   = t.value.substr(start, end-start);
		if (sel) {
			if (sel.indexOf("http://") < 0)
				text = "http://" + sel.trim();
			else
				text = sel.trim();
		}
	}

	var urlAddr = prompt('Введите адрес ссылки', text);
	if(urlAddr == null) return;
	if((urlAddr == '') || (urlAddr == 'http://')) { alert('Адрес ссылки введён не верно'); return; };

	return "url="+urlAddr;
}


function getInsertPopupDoc()
{	//var ifw = window.frames["popupsIframe"];
	var pif = document.getElementById('popupsIframe'); 
	if (!pif) {
		alert('no popup frame!');	
	}
	var insertPopupDoc = pif.contentDocument || pif.contentWindow.document || pif.document; // get frame document	 
	if (!insertPopupDoc) {
		alert('popup window is not exists');		
	}
	return insertPopupDoc;	
}

function createInsertPopup(url) 
{
	return $('<div/>', {
		"class": "insimage",
		"id": "insimage"
	}).append(
		$('<iframe/>', {
			"id": "popupsIframe",
			"name": "popupsIframe",
			"width": "100%",
			"height": "100%",
			"frameborder": "0",
			"src": url
		})
	);
}

function OpenInsertPopup()
{	
	var popup = document.getElementById('insimage');
	if (popup) {
		$(popup).find('#popupsIframe').attr('src', this.href);
		return false;
	}
	var popup = createInsertPopup(this.href);
	popup.appendTo('body').show('fast');	
	return false;
}

function CloseInsertPopup()
{	
	var ifb = document.getElementById('insimage');
	if (ifb) {
		document.body.removeChild(ifb);
	}
	return false;	
}

function SetupPopupHandlers() 
{		
	var fdoc = getInsertPopupDoc();
	el = fdoc.getElementById("fromurl");
	if (el) el.onclick = function () { return selectRadio("fromurl"); }
	selectRadio('fromurl');
	
	el = fdoc.getElementById("fromfile");
	if (el) el.onclick = function () { return selectRadio("fromfile"); }	
}

function selectRadio(which) 
{
	var fdoc = getInsertPopupDoc();
	var fromfile  = fdoc.getElementById('inpFromFile');
	var fromfiledesc  = fdoc.getElementById('inpFileDescr');
	var fromurl = fdoc.getElementById('inpFromUrl');
	var submit   = fdoc.getElementById('btnInsert');
	var radio = fdoc.getElementById(which);
	radio.checked = true;
	
	if (which == "fromurl") {
		submit.value = 'Вставить';
		fromurl.disabled = false;
		fromfiledesc.disabled = true;
		fromfile.disabled = true;
		fromurl.focus();
	}
	else if (which == "fromfile") {
		submit.value = 'Загрузить';
		fromurl.disabled = true;
		fromfiledesc.disabled = false;
		fromfile.disabled = false;		
		fromfile.focus();
	}	
	return true;	
}

function InsertImage()
{
	var fdoc = getInsertPopupDoc();
	if (fdoc.getElementById('fromurl').checked) 
	{
		var inpFromUrl = fdoc.getElementById('inpFromUrl');
		var url = trim(inpFromUrl.value);
		if (url.trim().length == 0) {
			alert('Адрес изображения не указан.');
			inpFromUrl.focus();
			return false;
		}
		if (url == 'http://' || url.length < 12) {
			alert('Адрес изображения указан неверно.');
			inpFromUrl.focus();
			return false;
		}
		if (url.indexOf('http://') < 0) {
			url = 'http://'+url;
		} 
		bbcode.insertAtCursor('[img]'+url+'[/img]');
		CloseInsertPopup();			
	}
	else if (fdoc.getElementById('fromfile').checked) 
	{
		var url = trim(fdoc.getElementById('inpFromFile').value);
		if (url.trim().length == 0) {
			alert('Не выбран файл для загрузки.');
			fdoc.getElementById('inpFromFile').focus();
			return false;
		}
		return true;
	}
	
	return false;
}

function InsertUplodedImage(src)
{
	if (!bbcode) { alert('bbcode is not ready;'); return false; }	
	bbcode.insertAtCursor('[photo]'+src+'[/photo]');
	CloseInsertPopup();
}


function InsertVideo(el)
{ 
	var text = '';
	var t = bbcode.textarea;
	if (t.setSelectionRange) {
		var start = t.selectionStart;
		var end   = t.selectionEnd;
		var sel   = t.value.substr(start, end-start);
		if (sel) {
			if (sel.indexOf("http://") < 0)
				text = "http://" + sel.trim();
			else
				text = sel.trim();
		}
	}
	
	var urlAddr = prompt('Введите адрес ролика', text);
	if (urlAddr == null) return;
	if (urlAddr.length == 0) { alert('Извините, но похоже адрес указан неверно.'); return; };	
	
	bbcode.insertAtCursor("[video]"+urlAddr+"[/video]");
}


function CutText(el)
{
	var text = '';
	var t = bbcode.textarea;
	if (t.setSelectionRange) {
		var start = t.selectionStart;
		var end   = t.selectionEnd;
		var text  = t.value.substr(start, end-start);
	}
	var cutTitle = prompt('Введите заголовок для скрываемого текста');
	return "cut"+(cutTitle ? ' '+cutTitle : '');
}

function InsertSmile(code)
{
	var area = window.document.getElementById("answerArea");
	bbcode.insertAtCursor(" "+code+" ");
	smilesHint.hide();
}

function NotifyModeratorBox(messageId)
{
	$('#nm_' + messageId).toggle('slow');
}

function NotifyModerator(messageId, wwwUrl)
{
	var messageId = messageId;
	var subject = $('#mnt_' + messageId).val();
	if (trim(subject) == '')
	{
		alert('Укажите причину жалобы.');
		return;
	}
	var url = wwwUrl + '/ajax/notify-moderator/';
	
	$.ajax({
		url: url,
		type: "POST",
		data: ({subject: subject, messageId: messageId}),
		dataType: "html",
		timeout: 30000,
		success: function(data, textStatus, XMLHttpRequest)
		{
			if (data == '0')
			{
				$('#nmw_' + messageId).hide(100);
				$('#nmb_' + messageId).show(100);
				$('#nm_' + messageId).toggle('slow');
				alert('Уведомление модератору отправлено. Спасибо.');
			}
			else
			{
				alert(data);
				$('#nmw_' + messageId).hide(100);
				$('#nmb_' + messageId).show(100);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			alert('Во время выполнения запроса произошла ошибка. Попробуйте еще раз.');
			$('#nmw_' + messageId).hide(100);
			$('#nmb_' + messageId).show(100);
		}
	});
	$('#nmw_' + messageId).show(100);
	$('#nmb_' + messageId).hide(100);
}

/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/
 
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
