//**
//** /dk_improve/js/common.js
//**

// Multiple onload callback support.
(function() {
  var onloads = [];
  window.attachOnload = function(func) {
    onloads[onloads.length] = func;
  }
  window.executeOnloads = function() {
    for (var i=0; i<onloads.length; i++) onloads[i]();
  }
})();

// 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;
}

//**
//** /dk_improve/js/bbcode.js
//**

// BBCode control.
function BBCode(textarea) { this.construct(textarea) }
BBCode.prototype = {
  BRK_OP:     '[',
  BRK_CL:     ']',
  textarea:   null,
  stext:      '',
  quoter:     null,
  collapseAfterInsert: false,
  replaceOnInsert: false,
  
  // Create new BBCode control.
  construct: function(textarea) {
    this.textarea = textarea 
    this.tags     = new Object();
    // Tag for quoting.
    this.addTag(
      '_quoter', 
      function() { return '[quote="'+th.quoter+'"]' }, 
      '[/quote]\n', 
      null, 
      null, 
      function() { th.collapseAfterInsert=true; return th._prepareMultiline(th.quoterText) }
    );

    // Init events.
    //var th = this;
    //addEvent(textarea, 'onkeydown',   function(e) { return th.onKeyPress(e, window.HTMLElement? 'down' : 'press') });
    //addEvent(textarea, 'onkeypress',  function(e) { return th.onKeyPress(e, 'press') });
  },

  // Insert poster name or poster quotes to the text.
  onposter: function(name) {
	var rt    = this.getSelection();
    var text  = rt[0];
	name = name.replace(" ","'");
	if (text=='')
	{
		this.insertAtCursor('[b]' + name + '[/b], ');
		return false;
	}
	else
	{
		this.insertAtCursor('[quote="' + name +'"]' + text + '[/quote]');
		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) {
    var tag = new Object();
    tag.id        = id;
    tag.open      = open;
    tag.close     = close;
    tag.elt       = this.textarea.form[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);
	this.surround(op, cl, null);
  },

  _prepareMultiline: function(text) {
    text = text.replace(/\s+$/, '');
    text = text.replace(/^([ \t]*\r?\n)+/, '');
    if (text.indexOf("\n") >= 0) text = "\n" + text + "\n";
    return text;
  }
  
}

// Called before form submitting.
function checkForm(form) {
  var formErrors = false;   
  if (form.message.value.length < 2) {
    formErrors = "Please enter the message.";
  }
  if (formErrors) {
    setTimeout(function() { alert(formErrors) }, 100);
    return false;
  }
  return true;
}

function crep(name,value)
{
	e=document.getElementsByTagName("span")
	for (var i=0;i<e.length;i++) if (e[i].className==name) e[i].innerHTML=value
}
function vrep(name,value)
{
	vote_mas = new Array('-3','-2','-1','0','+1','+2','+3')
	vote_str = '';
	for (i=0;i<vote_mas.length;i++)
	{
		vote_str += (vote_mas[i]==value) ? vote_mas[i] + '|' : '<a href="#charisma" onclick="charisma.send(\'' + name + '\', \'' + vote_mas[i] + '\'); return false">' + vote_mas[i] + '</a>|'
	}
	value = vote_str
	name = "pid_" + name

	e=document.getElementsByTagName("span")
	for (var i=0;i<e.length;i++) if (e[i].className==name) e[i].innerHTML=value
}

charisma = {
  send: function(poster_id, type) {
    var req = new Subsys_JsHttpRequest_Js();
	req.onreadystatechange = function() {
		if (req.readyState == 4)
			{
			if (req.responseJS)
				{
if (req.responseJS.err=="")
{
sp_charisma = "c_" + req.responseJS.uid
newc = req.responseJS.cnew
alert ( req.responseJS.mess )
crep ( sp_charisma, newc )
vrep ( req.responseJS.uid, req.responseJS.val )
}
else
{
alert ( req.responseJS.err )
}
				}
			}
		}
	
	req.SID = window.SID;
    req.open('GET', 'load_charisma.php?sid='+window.SID, true);
    req.send({ 'p': poster_id, 'x': type });
  }
}


$(document).ready(function () {
	M = $("#menu");
	//M.width("auto");
	Mw = M.width();
	M.css({width:Mw+100, marginLeft:-(Mw/2+50)})
	C = $("#Container");
	mo = 0;
	wo = 0;
	$(".button", M).toggle(function() {
		M.animate({marginTop:0}).get(0).className = "open";
		mo = 1;
	}, function() {
		M.animate({marginTop:"-163px"}).get(0).className = "";
		mo = 0;
	}).css({left:(Mw+100)/2-68});
});
