var d = document;
var ie=d.all && !window.opera;
var ns6=d.getElementById && !d.all;
var obj,op,c;
var a = new Array();

function getNewspaper(flash, pdf) {
    if (playerVersion >= 9) {
        url = flash;
    } else {
        url = pdf;
    };
    window.open(url);
}

function showPeriodspecify(el) {
  obj = d.getElementById('periodspecify_box_' + el.value);
  if (obj.style.display == 'none' || obj.style.display == '') {
    for (var i=1; i<5; i++) {
      d.getElementById('periodspecify_box_' + i).style.display = 'none';
    }
    obj.style.display = 'block';
  }
}

function showSubLine(el) {
    l = el;
    lp = getParent(el);
    lc = getChild(el);
    l.className = 'hovered';
    
    var node = getParent(el);
    addHandler(node, 'mouseout', function(e) {
        var target = e.relatedTarget || e.toElement;
        if(target != lp && target != lc && target != l) {
            l.className = '';
        }
    });
}

function showSubMenu(el,id) {
    obj = d.getElementById(id);
    c = obj.className;
    vis = obj.style.visibility;
    if(vis == 'hidden') {
        op = 0.1;
        obj.style.opacity = op;
        obj.style.visibility="visible";
        appear();
    }
    
    l = el;
    lp = getParent(el);
    lc = getChild(el);
    l.className = 'hovered';
    
    po = obj.getElementsByTagName('div');
    var identifier = new RegExp('(^| )'+'pointer'+'( |$)');
    
    for(var q = 0; q < po.length; q++) {
        if(identifier.test(po[q].className)) {
            setPointer(el,po[q]);
        }
    }
    
    var node = getParent(el);
    addHandler(node, 'mouseout', function(e) {
        var target = e.relatedTarget || e.toElement;
        if(!isParent(target,node)) {
            hideSubMenu(node,l,target);
        }
        else {
            if(target != lp && target != lc && target != l) {
                l.className = '';
                if (target.nodeName == 'LI') {
                    li = getChild(target);
                    li.className = 'hovered';
                }
                else if (target.nodeName == 'P') {
                    li = getParent(target);
                    li.className = 'hovered';
                }
                else {
                    li = target;
                    li.className = 'hovered';
                }
            }
        }
    });
}
 
function hideSubMenu(parent,l,el) {
    if(el == obj || isOffsetParent(el, obj)) {
        addHandler(obj, 'mouseout', function(e) {
            var target = e.relatedTarget || e.toElement;
            if(isParent(target, parent) || isOffsetParent(target, obj)) {
                if (isParent(target, parent)) {
                    lp = getParent(l);
                    lc = getChild(l);
                    if(target != lp && target != lc && target != l) {
                        l.className = '';
                        if (target.nodeName == 'LI') {
                            li = getChild(target);
                            li.className = 'hovered';
                        }
                        else if (target.nodeName == 'P') {
                            li = getParent(target);
                            li.className = 'hovered';
                        }
                        else {
                            li = target;
                            li.className = 'hovered';
                        }
                    }
                }
            }
            else {
                l.className = '';
                obj.style.visibility='hidden';
            }
        });
    }
    else {
        l.className = '';
        obj.style.visibility='hidden';
    }
}
 
function ietruebody(){
return (d.compatMode && d.compatMode!="BackCompat")? d.documentElement : d.body
}

function setPosition(el){
    var winwidth=ie? ietruebody().clientWidth : window.innerWidth
    var winheight=ie? ietruebody().clientHeight : window.innerHeight
    w = el.clientWidth/2;
    h = el.clientHeight/2;
    el.style.top = winheight/2 - h + 'px';
    el.style.left = winwidth/2 - w + 'px';
}

function PW_show(el,file) {
    
}

function show() {
    if(typeof arguments[0] == 'string')
        obj = document.getElementById(arguments[0]);
    else
        obj = arguments[0];
    if (d.getElementById('shadow')) {
        p = d.getElementById('shadow');
        p.style.display="block";
    }
    vis = obj.style.visibility;
    if(vis == 'hidden' || vis == '') {
        obj.style.visibility = 'visible';
        if (!op) op = 0;
        else op = obj.style.opacity;
        appear();
    }
}

function hide() {
    if(typeof arguments[0] == 'string')
        obj = document.getElementById(arguments[0]);
    else
        obj = arguments[0];
    if (d.getElementById('shadow')) {
        p = d.getElementById('shadow');
        p.style.display="none";
    }
    vis = obj.style.visibility;
    if(vis == 'visible') {
        if (!op) op = 1;
        else op = obj.style.opacity;
        disappear();
    }
}

function appear() {
    if(op < 1) {
        op = op - 0 + 0.1;
        obj.style.opacity = op;
        obj.style.filter = 'alpha(opacity='+op*100+')';
        t = setTimeout('appear()', 30);
    }
}

function disappear() {
    if(op > 0) {
        op = op - 0.1;
        obj.style.opacity = op;
        obj.style.filter = 'alpha(opacity='+op*100+')';
        t = setTimeout('disappear()', 30);
    }
    if(op < 0.1) {
        obj.style.visibility="hidden";
    }
}

function addHandler(node, evt, func) {
    if (node.addEventListener) {
        node.addEventListener(evt, func, false);
    } else {
        node.attachEvent('on' + evt, func);
    }
};

function removeHandler(node, evt, func) {
    if (node.removeEventListener) {
        node.removeEventListener(evt, func, false);
    } else {
        node.detachEvent('on' + evt, func);
    }
};

function isParent(child, parent) {
    if (!child || !parent) {
        return false;
    }
    while (true) {
        if (child == parent) {
            return true;
        }
        if (child.parentElement) {
            child = child.parentElement;
        } else if (child.parentNode) {
            child = child.parentNode;
        } else {
            return false;
        }
    }
}

function isOffsetParent(child, parent) {
    if (!child || !parent) {
        return false;
    }
    while (true) {
        if (child == parent) {
            return true;
        }
        if (child.offsetParent) {
            child = child.offsetParent;
        } else {
            return false;
        }
    }
}

function whosChild(child) {
    if (!child) {
        return false;
    }
    while (true) {
        if (child.parentElement) {
            return child.parentElement.parentElement;
        } else if (child.parentNode) {
            return child.parentNode.parentNode;
        } else {
            return false;
        }
    }
}

function getParent(child) {
    if (!child) {
        return false;
    }
    while (true) {
        if (child.parentElement) {
            return child.parentElement;
        } else if (child.parentNode) {
            return child.parentNode;
        } else {
            return false;
        }
    }
}

function getChild(parent) {
    if (!parent) {
        return false;
    }
    while (true) {
        if (parent.firstElementChild) {
            return parent.firstElementChild;
        } else {
            return false;
        }
    }
}

function setPointer(e,el) {
    w = ie? e.clientWidth : e.offsetWidth
    left = e.offsetLeft;
    p = left - 55 + w/2 - 9 + 'px';
    el.style.backgroundPosition = p;
}

function generatePopupContent(id,a)
{
    var el;
    var parent = document.getElementById(id);
    
    if(parent.children.length > 0) {
        return false;
    }
    else {
        leftColumn = document.createElement('div');
        leftColumn.setAttribute('class','column fl');
        parent.appendChild(leftColumn);
        
        if(a[0] != '') {
            leftDiv = document.createElement('div');
            leftDiv.setAttribute('class','sub-rub fl');
            leftColumn.appendChild(leftDiv);
            
            for(var i=0; i<a[0].length; i++) {
                if(a[0][i][1]) {
                    el = document.createElement('a');
                    el.innerHTML = a[0][i][0];
                    el.setAttribute('href',a[0][i][1]);
                    leftDiv.appendChild(el);
                }
                else
                {
                    el = document.createElement('p');
                    el.innerHTML = a[0][i][0];
                    leftDiv.appendChild(el);
                }
            }
        }
        
        rightDiv = document.createElement('div');
        rightDiv.setAttribute('class','news fl');
        leftColumn.appendChild(rightDiv);
        
        pTitle = document.createElement('p');
        pTitle.innerHTML = a[1][0];
        pTitle.setAttribute('class','title');
        rightDiv.appendChild(pTitle);
        
        for(var i=1; i<a[1].length; i++) {
            if(a[1][i][1]) {
                el = document.createElement('a');
                el.innerHTML = a[1][i][0];
                el.setAttribute('href',a[1][i][1]);
                rightDiv.appendChild(el);
                
                el = document.createElement('p');
                el.innerHTML = a[1][i][2];
                el.setAttribute('class','date');
                rightDiv.appendChild(el);
            }
            else
            {
                el = document.createElement('p');
                el.innerHTML = a[1][i][0];
                rightDiv.appendChild(el);
                
                el = document.createElement('p');
                el.innerHTML = a[1][i][2];
                el.setAttribute('class','date');
                rightDiv.appendChild(el);
            }
        }
        
        moreDiv = document.createElement('div');
        moreDiv.setAttribute('class','more');
        leftColumn.appendChild(moreDiv);
        
        if(a[2][1]) {
            el = document.createElement('a');
            el.innerHTML = a[2][0];
            el.setAttribute('href',a[2][1]);
            moreDiv.appendChild(el);
        }
        else
        {
            el = document.createElement('p');
            el.innerHTML = a[2][0];
            moreDiv.appendChild(el);
        }
        
        rightColumn = document.createElement('div');
        rightColumn.setAttribute('class','column-last fr');
        parent.appendChild(rightColumn);
        
        hTitle = document.createElement('h1');
        rightColumn.appendChild(hTitle);
        
        if(a[3][1]) {
            el = document.createElement('a');
            el.innerHTML = a[3][0];
            el.setAttribute('href',a[3][1]);
            hTitle.appendChild(el);
        }
        else
        {
            el = document.createElement('p');
            el.innerHTML = a[3][0];
            hTitle.appendChild(el);
        }
        
        el = document.createElement('p');
        el.innerHTML = a[3][2];
        el.setAttribute('class','date');
        rightColumn.appendChild(el);
        
        if(a[3][1]) {
            aImage = document.createElement('a');
            aImage.setAttribute('href',a[3][1]);
            aImage.setAttribute('class','image fr');
            rightColumn.appendChild(aImage);
        }
        else
        {
            aImage = document.createElement('p');
            aImage.setAttribute('class','image fr');
            rightColumn.appendChild(aImage);
        }
        
        el = document.createElement('img');
        el.setAttribute('class','image-fix');
        el.setAttribute('src',a[3][3]);
        aImage.appendChild(el);
        
        el = document.createElement('p');
        el.innerHTML = a[3][4];
        rightColumn.appendChild(el);
        
        el = document.createElement('div');
        el.setAttribute('class','clear');
        parent.appendChild(el);
    }
}

function bbcodeComment(bbcode)
{
    var t=d.getElementById('comment_textarea');
    var formattedStr = "";
    var startPosition = 0;
    var endPosition = 0;
    
    var text = t.value;

    if (document.selection) {
        // Internet Explorer
        var range = document.selection.createRange();
        var dpl = range.duplicate();
        if (range.text.length > 0) {
            dpl.moveToElementText(a);
            dpl.setEndPoint("EndToEnd", range);
            startPosition = dpl.text.length-range.text.length;
            endPosition = startPosition + range.text.length;
        }
    }
    else {
        // Mozilla Firefox
        startPosition = t.selectionStart;
        endPosition = t.selectionEnd;
    }
    
    if (startPosition!=endPosition) {
        var sbStr = text.substring(startPosition,endPosition);
        sbStr = '['+bbcode+']'+sbStr+'[/'+bbcode+']';
    
        // split textarea value into three pieces: before startPosition,
        // startPosition until endPosition, and after endPosition
        var str1 = text.substring(0,startPosition);
        var str2 = text.substring(startPosition,endPosition);
        var str3 = text.substring(endPosition,text.length);
    
        // replace str2 with formatted substring (selectedText)
        str2 = sbStr;
        // form the new string
        formattedStr = str1+str2+str3;
        t.value = formattedStr;
        t.focus();
    }
    else
    {
        t.focus();
        t.value += '['+bbcode+'][/'+bbcode+']';
    }
}

function notEmpty(elem, helperMsg){
    if(elem.value.length == 0){
        alert(helperMsg);
        elem.focus();
        return false;
    }
    return true;
}

function isAlphanumeric(elem, helperMsg){
    var alphaExp = /^[0-9a-zA-Z_]+$/;
    if(elem.value.match(alphaExp)){
        return true;
    }else{
        alert(helperMsg);
        elem.focus();
        return false;
    }
}

function lengthRestriction(elem, min){
    var uInput = elem.value;
    if(uInput.length >= min){
        return true;
    }else{
        alert("Пароль не може бути коротшим за " +min+ " символів");
        elem.focus();
        return false;
    }
}

function emailValidator(elem, helperMsg){
    var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
    if(elem.value.match(emailExp)){
        return true;
    }else{
        alert(helperMsg);
        elem.focus();
        return false;
    }
}

function passValidator(elem1, elem2){
    if(elem1.value === elem2.value){
        return true;
    }else{
        alert("Паролі не співпадають");
        elem1.focus();
        return false;
    }
}

function checkform(){
    
    if(document.getElementById('login')) {
        var login = document.getElementById('login');
        if(!notEmpty(login, "Поле \"Логін\" повинно бути заповненим")){
            return false;
        }
        if(!isAlphanumeric(login, "Використовуйте лише латинські літери, цифри, \"-\" та \"_\" для логіна")){
            return false;
        }
    }
    if(document.getElementById('email')) {
        var email = document.getElementById('email');
        if(!emailValidator(email, "Будьласка введіть коректну адресу електронної пошти")){
            return false;
        }
    }
    if(document.getElementById('pass') && document.getElementById('pass_val')) {
        var pass = document.getElementById('pass');
        var pass_val = document.getElementById('pass_val');
        if(!notEmpty(pass, "Ви не ввели пароль")){
            return false;
        }
        if(!lengthRestriction(pass, 6)){
            return false;
        }
        if(!passValidator(pass, pass_val)){
            return false;
        }
    }
    
    return true;
    
}

function doFilter() {
    if(document.getElementById('filter_by_day')) {
        var day = document.getElementById('filter_by_day');
        var byday = day.value + "/";
    }
    else {
        var byday = "";
    }
    if(document.getElementById('filter_by_month')) {
        var month = document.getElementById('filter_by_month');
        var bymonth = month.value + "/";
    }
    else {
        bymonth = "";
    }
    if(document.getElementById('filter_by_year')) {
        var year = document.getElementById('filter_by_year');
        var byyear = year.value + "/";
    }
    else {
        byyear = "";
    }
    
    var protocol = window.location.protocol;
    var host = window.location.host;
    var pathname = window.location.pathname;
    
    window.location = protocol + "//" + host + pathname + "/" + byday + bymonth + byyear;
}

function changeInput(iden,type) {
    var el = document.getElementById(iden+"_value"), value;
    if (type != 'file') {
        value = el.innerHTML;
    }
    else {
        value = '';
    }
    var parent = el.offsetParent;
    parent.innerHTML = '';
    var input = document.createElement("input");
    input.setAttribute('type', type);
    input.setAttribute('class', type + ' login-' + type);
    input.setAttribute('name', iden);
    input.setAttribute('id', iden);
    input.setAttribute('value', value);
    parent.appendChild(input);
}

function changeAvatar(el) {
    parent = getParent(el);
    parent.removeChild(el);
    elem = document.getElementById('photo_edit');
    var input = document.createElement("input");
    input.setAttribute('type', 'file');
    input.setAttribute('class', 'file login-text');
    input.setAttribute('name', 'photo');
    input.setAttribute('id', 'photo');
    elem.appendChild(input);
}

var base_domain = base_domain || "/";
var _ua = navigator.userAgent.toLowerCase();
var browser = {
  version: (_ua.match( /.+(?:me|ox|on|rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
  opera: /opera/i.test(_ua),
  msie: (!this.opera && /msie/i.test(_ua)),
  msie6: (!this.opera && /msie 6/i.test(_ua)),
  msie8: (!this.opera && /msie 8/i.test(_ua)),
  mozilla: /firefox/i.test(_ua),
  chrome: /chrome/i.test(_ua),
  safari: (!(/chrome/i.test(_ua)) && /webkit|safari|khtml/i.test(_ua)),
  iphone: /iphone/i.test(_ua),
  ipod: /ipod/i.test(_ua),
  ipad: /ipad/i.test(_ua),
  safari_mobile: /iphone|ipod|ipad/i.test(_ua),
  mobile: /iphone|ipod|ipad|opera mini|opera mobi/i.test(_ua)
}

function isFunction(obj) { return Object.prototype.toString.call(obj) === "[object Function]"; }
function isArray(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }

function ge() {
  var ea;
  for (var i = 0; i < arguments.length; i++) {
    var e = arguments[i];
    if (typeof e == 'string')
      e = document.getElementById(e);
    if (arguments.length == 1)
      return e;
    if (!ea)
      ea = new Array();
    ea.push(e);
  }
  return ea;
}

function geByClass(searchClass, node, tag) {
  var classElements = new Array();
  if (node == null)
    node = document;
  if (tag == null)
    tag = '*';
  if (node.getElementsByClassName) {
    classElements = node.getElementsByClassName(searchClass);
    if (tag != '*') {
      for (i = 0; i < classElements.length; i++) {
        if (classElements.nodeName == tag)
          classElements.splice(i, 1);
      }
    }
    return classElements;
  }
  var els = node.getElementsByTagName(tag);
  var elsLen = els.length;
  var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
  for (i = 0, j = 0; i < elsLen; i++) {
    if ( pattern.test(els[i].className) ) {
      classElements[j] = els[i];
      j++;
    }
  }
  return classElements;
}

function ce(tagName, attr, inner) {
    var el = document.createElement(tagName);
    if (attr) {
    if ((options = attr) != null)
        for (var name in options) {
            var value = options[name];
            el.setAttribute(name, value);
        }
    }
    if (inner) {
      el.innerHTML = inner;
    }
    return el;
}

function each(object, callback) {
  var name, i = 0, length = object.length;

  if ( length === undefined ) {
    for ( name in object )
      if ( callback.call( object[ name ], name, object[ name ] ) === false )
        break;
  } else
    for ( var value = object[0];
      i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}

  return object;
};

function getXY(obj) {
    if (!obj || obj == undefined) return;
    var left = 0, top = 0;
    if (obj.offsetParent) {
        do {
            left += obj.offsetLeft;
            top += obj.offsetTop;
        }
        while (obj = obj.offsetParent);
    }
    return [left,top];
}


function getSize(elem, withoutBounds) {
  var s = [0, 0];
  if (elem == document) {
    s =  [Math.max(
        document.documentElement["clientWidth"],
        document.body["scrollWidth"], document.documentElement["scrollWidth"],
        document.body["offsetWidth"], document.documentElement["offsetWidth"]
      ), Math.max(
        document.documentElement["clientHeight"],
        document.body["scrollHeight"], document.documentElement["scrollHeight"],
        document.body["offsetHeight"], document.documentElement["offsetHeight"]
      )];
  } else if (elem){
    function getWH() {
      s = [elem.offsetWidth, elem.offsetHeight];
      s = [Math.round(s[0]), Math.round(s[1])];
    }
    if (!isVisible(elem)) {
      var props = {position: "absolute", visibility: "hidden", display:"block"};
      var old = {};
      each(props, function(i, val){
        old[i] = elem.style[i];
        elem.style[i] = val;
      });
      getWH();
      each(props, function(i, val){
        elem.style[i] = old[i];
      });
    } else getWH();

  }
  return s;
}

// Extending object by another
function extend() {
  var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;

  if (typeof target === "boolean") {
    deep = target;
    target = arguments[1] || {};
    i = 2;
  }

  if (typeof target !== "object" && !isFunction(target))
    target = {};

  if (length == i) {
    return target;
  }

  for (; i < length; i++)
    if ((options = arguments[i]) != null)
      for (var name in options) {
        var src = target[name], copy = options[name];

        if (target === copy)
          continue;

        if (deep && copy && typeof copy === "object" && !copy.nodeType)
          target[name] = extend(deep,
            src || (copy.length != null ? [] : { })
          , copy);

        else if (copy !== undefined)
          target[name] = copy;
      }
  return target;
}

function hasClass(obj, name) {
    obj=ge(obj);
    return obj && (new RegExp('(\\s|^)' + name + '(\\s|$)')).test(obj.className);
}

function isVisible(elem) {
    elem = ge(elem);
    return getStyle(elem, 'display') != 'none' && getStyle(elem, 'visibility') != 'hidden';
}

function createButton(el, onClick, classPrefix, initOnHover) {
    el = ge(el);
    if (!el) return;
    if (initOnHover && el.btnInited) return;
    if (classPrefix == undefined) classPrefix = 'button';
    var buttonClass = (hasClass(el.parentNode, 'button_yes') ? 'button_yes' : (hasClass(el.parentNode, 'button_no') ? 'button_no' : ''));
    var upd = function(state) {
        if (buttonClass) {
            var a = button_anims[buttonClass][state];
            animate(el, {backgroundColor: a.p[0], borderTopColor: a.p[1], borderRightColor: a.p[2], borderBottomColor: a.p[3], borderLeftColor: a.p[4]}, a.o);
        }
        else {
            el.className = classPrefix + state;
        }
    }
    var hover = false;
    $(el).bind('click', function(e) {
        if (isFunction(onClick)) return onClick(e);
    });
    if (initOnHover) {
        upd('_hover');
        hover = true;
    }
    el.btnInited = true;
}



var _message_box_guid = 0,
    _message_boxes = [],
    _message_box_shown = 0,
    _doc_block_timeout, _doc_blocked = false;
function MessageBox(options) {
    var defaults = {
    type: "message", // "message" || "popup"
    hideOnClick: true,
    title: "Alert",
    width: "410px",
    height: "auto",
    bodyStyle: "",
    closeButton: false, // AntanubiS - 'X' close button in the caption.
    fullPageLink: '', // If is set - 'box'-like button in the caption.
    progress: false, // AntanubiS - Progress bar.
    returnHidden: false // AntanubiS - When hide - return previously hidden box.
  };

  options = extend(defaults, options);

    var buttonsCount = 0, body = document.getElementsByTagName('body')[0],
        shadow, boxContainer, boxBG, boxLayout, boxTitle, boxBody, boxControls, boxProgress, buttonYes, buttonNo, boxCloseButton, boxFullPageLink,
        guid = (++_message_box_guid), isVisible = false, hiddenBox;
    
    shadow = ge('shadow');
    if (!shadow) {
        shadow = ce('div', {id: 'shadow', class: 'shadow'}, '<iframe class="box_frame"></iframe>');
        body.appendChild(shadow);
    }
    if (shadow&&shadow.style.display!="block") {
        shadow.style.display="block";
    }
    
    var x_button = options.closeButton ? '<div class="box_x_button"></div>' : '';
    var full_page_button = options.fullPageLink ? '<a onfocus="this.blur()" class="box_full_page_link" href="' + options.fullPageLink + '"></a>' : '';
    boxContainer = ce('div', { class: 'popup_box_container' }, '<div class="box_layout"><div class="box_title_wrap">' + x_button + full_page_button + '<div class="box_title">' + options.title + '</div></div><div class="box_body" style="'+options.bodyStyle+'"></div><div class="box_controls_wrap"><div class="box_controls"></div></div></div>');
    
    boxFrame = geByClass('box_frame', shadow)[0];
    boxLayout = geByClass('box_layout', boxContainer)[0];
    boxTitle = geByClass('box_title', boxContainer)[0];
    boxBody = geByClass('box_body', boxContainer)[0];
    boxControls = geByClass('box_controls', boxContainer)[0];
    boxCloseButton = options.closeButton ? geByClass('box_x_button', boxContainer)[0] : false;
    boxFullPageLink = options.fullPageLink ? geByClass('box_full_page_link', boxContainer)[0] : false;
    
    if (options.progress) {
        boxControls.innerHTML = '<img src="' + base_domain + 'images/upload.gif" id="' + options.progress + '" style="display: none" />';
        boxProgress = boxControls.firstChild;
    }
    else {
        boxProgress = null;
    }
    
    // Add button
    function addButton(options) {
        buttonsCount++;
        if (typeof options != 'object') options = {};
        options = extend({
            label: 'Button' + buttonsCount,
            style: 'button_yes'
        }, options);
        
        var buttonWrap = ce('div', {class: options.style}, '<div id="button' + guid + '_' + buttonsCount + '">' + options.label + '</div>');
        if (boxProgress) {
            boxControls.insertBefore(buttonWrap, boxProgress);
        }
        else {
            boxControls.appendChild(buttonWrap);
        }
        createButton(buttonWrap.firstChild, options.onClick);
        return buttonWrap;
    }
    
    // Add custom controls text
    function addControlsText(text) {
        var textWrap = ce('div', {class: 'controls_wrap'}, text);
        boxControls.appendChild(textWrap);
        return textWrap;
    }
    
    // Remove buttons
    function removeButtons() {
        var buttons = [];
        buttonsCount = 0;
        each (boxControls.childNodes, function(i, x) {
            if (x && (!boxProgress || x != boxProgress)) {
            removeHandler(x);
            buttons.push(x);
            }
        });
        each(buttons, function() {boxControls.removeChild(this)});
        // boxControls.innerHTML = '';
    }
    
    // Show box
    function showBox() {
        if (isVisible) return;
        isVisible = true;
        hiddenBox = 0;
        
        if (_message_box_shown && _message_boxes[_message_box_shown].isVisible) {
            var box = _message_boxes[_message_box_shown];
            if (options.returnHidden) {
                hiddenBox = _message_box_shown;
                box.hideContainer();
            }
            else {
                box.hide();
            }
        }
        
        if(!_message_box_shown && !_doc_blocked) {
            body.appendChild(boxContainer);
            show(boxContainer);
        }
        else {
            show(boxContainer);
            if (!_doc_blocked) {
                _doc_blocked = true;
            }
        }
        
        _message_box_shown = guid;
        
        if (options.onShow)
            options.onShow();
    }
    
    function hideBox() {
        if (!isVisible) return;
        if (options.onHideAttempt && !options.onHideAttempt()) return;
        isVisible = false;
        
        var onHide = function () {
            hide(boxContainer);
            var showHidden = false;
            if (options.returnHidden && hiddenBox) {
                _message_boxes[hiddenBox].showContainer();
                _message_box_shown = hiddenBox;
                showHidden = true;
            }
            if (!showHidden) {
                _message_box_shown = 0;
                if (_doc_blocked) {
                    _doc_block_timeout = setTimeout(function() {
                        _doc_blocked = false;
                    }, 50);
                }
            }
            if (options.onHide) options.onHide();
        }
        onHide();
    }
    
    var retBox = {
    guid: guid,

    show: function() {
      showBox(); return this;
    },
    // Hide box
    hide: function() {
      hideBox(); return this;
    },
    
    // Load html content from URL
    loadContent: function(url, params, evaluate, loader_style, noloader) {
        // Show loader
        var st = loader_style ? loader_style : '';
        if (!noloader) boxBody.innerHTML = '<div class="box_loader" style="' + st + '"></div>';
        
        // Load remote html using get request
        if (typeof params != 'object') params = {};
        var self = this;
        $.ajax({
            url: "change_avatar.html",
            cache: false,
            success: function(html){
                boxBody.innerHTML = html;
            }
        });
        
        return this;
    },

    // Add button
    addButton: function(options) {
      var btn = addButton(options);
      return (options.returnBtn) ? btn : this;
    },
    // Add
    addControlsText: function(text) {
      var el = addControlsText(text);
      return (options.returnBtn) ? el : this;
    },

    // Remove buttons
    removeButtons: function(options) {
      removeButtons();
      return this;
    },
    //fixIE6: refreshBox,
    hideContainer: function() { isVisible = false; hide(boxContainer); },
    showContainer: function() { isVisible = true; show(boxContainer); },
    body: function() { return boxBody; }
  };
  _message_boxes[guid] = retBox;
  return retBox;
}
/*
( function () {
    var photoEditBox;
    window.loadNewPhoto = function() {
        var el = arguments[0];
        if (!photoEditBox) {
            var box = new MessageBox({ title: 'profileEdit_photo_upload_photo', progress: 'load_new_photo_progress' });
            box.addButton({ label: 'box_cancel', onClick: function() { box.hide(); }, style: 'button_no' });
            box.addButton({ label: 'profile_load', onClick: function() {
                if (ge('photo').value != '') {
                    show('load_new_photo_progress');
                    ge('transport_iframe').innerHTML = '<iframe name="transport"></iframe>';
                    ge('editPhoto').submit();
                }
            }});
            var boxHeight = 188;
            boxHeight += browser.mozilla ? -1 : browser.chrome ? 1 : browser.opera ? -4 : browser.safari ? 1 : browser.msie8 ? -5 : -7;
            box.loadContent('profileEdit.html', null, true, 'height: ' + boxHeight + 'px;');
            photoEditBox = box;
        }
        //hide('load_new_photo_progress');
        if (ge('messageWrap')) hide('messageWrap');
        if (ge('transport_iframe')) ge('transport_iframe').innerHTML = '<iframe name="transport"></iframe>';
        if (ge('photo')) ge('photo').value = '';
        if (photoEditBox) photoEditBox.show();
    }
})();*/
