var isOpera = Boolean(window["opera"]);
var isIE = (navigator.appName.indexOf("Microsoft") != -1) && !isOpera;
var isIE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
var isIE7 = false /*@cc_on || @_jscript_version == 5.7 @*/;
// not dependent on rendering mode
var isIE8 = (navigator.appName == 'Microsoft Internet Explorer' && navigator.userAgent.match(/Trident\/4/));

function uPicOver(span) {
    var avatarPath, img;
    avatarPath = "http://avt.foto.mail.ru/";
    img = document.getElementById("forUserPicShow");
    img.src = avatarPath + span.id + "/_avatar";
    img.style.top = absPosition(span).y + span.offsetHeight;
    img.style.left = absPosition(span).x;
    img.style.display = "";
}

function uPicOut(span) {
    var img;
    var img = document.getElementById("forUserPicShow");
    img.style.display = "none";
    img.src = "wait.gif";

}

function gebi(eid) { return document.getElementById(eid) }
function $(el) { return (typeof el == 'string') ? document.getElementById(el) : el }

function absPosition(obj) { // Определяем top - left координаты блока obj
    var ox = 0;
    var oy = 0;
    while ( obj ) {
        ox += obj.offsetLeft;
        if (Theme_tmpl) {
        //только для ИЕ, для выпадающего меню рядом с пользоватетем и для постов!!! сделано так потому что неправильно определяются координаты из-за позиционирования родительских блоков
            if (navigator.appName == "Microsoft Internet Explorer" && obj.nodeName == "A" && obj.id == "post_menu") {
                oy += 1;
            } else {
               oy += obj.offsetTop;
            }
        } else {
            oy += obj.offsetTop;
        }
        //  В некоторых случаях почему-то для элемента на странице отсутствует офсет
        if ( obj.offsetParent == null ) {
            obj = obj.nodeName == 'BODY' ?  null : obj.parentNode;
        }

        if ( obj != null ) obj = obj.offsetParent;
    }
    return {x:ox,y:oy};
}

function check_winsize() {
    var size;
    if (document.all) {
        size=window.document.body.clientWidth;
    } else {
        size = window.innerWidth;
    }
    if (size>820){
        document.getElementById("zapis_div").style.width=size*0.63;
    } else {
        document.getElementById("zapis_div").style.width=500;
    }
}

function show_add_to_friends_on_load() {
    if (window.location.search.indexOf('show_add_to_friend=1')>=0)
        show_friend_group_selector('for_friend_group_selector',PerlVar_JournalEmail);
}

function get_back_param_str() {
    return encodeURIComponent(document.getElementById("back_param_input").value);
}

/* попапы */

var popup_l = false;
//функция для отображения popup окна, при нажатии на ссылку  "увеличить" под аватаром
function popup_larger(Url) {
    if (popup_l) popup_l.close();
    popup_l = window.open(Url,'popup','width=580,height=580,toolbars=no,scrollbars=yes,resizable=yes,left='+(screen.width-580)/2+',top='+(screen.height-580)/2);
    if (popup_l) popup_l.focus();
}

/* mp3 player*/

function embed_mp3_player(URL) {
   // Get Operating System
   var isWin = navigator.userAgent.toLowerCase().indexOf("windows") != -1;
   if (isWin) { // Use MIME type application/x-mplayer2
      visitorOS="Windows";
   } else { // Use MIME type audio/mpeg, audio/x-wav, etc.
      visitorOS="Other";
   }

   var objTypeTag = "application/x-mplayer2"; // The MIME type to load the WMP plugin in non-IE browsers on Windows
   if (visitorOS != "Windows") { objTypeTag = "audio/mpeg"}; // The MIME type for Macs and Linux

   document.writeln("<div>");
   document.writeln("<object width='280' height='69'>"); // Width is the WMP minimum. Height = 45 (WMP controls) + 24 (WMP status bar)
   document.writeln("<param name='type' value='" + objTypeTag + "'>");
   document.writeln("<param name='src' value='" + URL + "'>");
   document.writeln("<param name='autostart' value='0'>");
   document.writeln("<param name='showcontrols' value='1'>");
   document.writeln("<param name='showstatusbar' value='1'>");
   document.writeln("<embed src ='" + URL + "' type='" + objTypeTag + "' autoplay='false' autostart='0' width='280' height='69' controller='1' showstatusbar='1' bgcolor='#ffffff'></embed>");

   // Firefox and Opera Win require both autostart and autoplay
   document.writeln("</object>");
   document.writeln("</div>");
}

/* journal */

function has_javascript() { return true }

function black_list_confirm(url,action,username) {
    if (action=="add") {
        if (confirm("Добавить "  + username + " в Черный список? ")) {
            location="http://" + PerlVar_BlogsPerlHost +url;
        }
    } else {
        if (confirm("Удалить " + username + " из Черного списка?")) {
            location="http://" + PerlVar_BlogsPerlHost +url;
        }
    }
}

function get_cookie(name) {
    var prefix = name + "=";
    var start = document.cookie.indexOf(prefix);
    if (start == -1) return null;
    start += prefix.length;
    var end = document.cookie.indexOf(";", start);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(start, end));
}

function set_cookie(name, value) {
    var cookie = name + "=" + escape(value) + ";expires=Sun, 31-Dec-34 23:59:59 GMT;path=/";
    if (cookie.length <= 4000) document.cookie = cookie;
}

function screen_post_callback(result, id, to_screen) {
    if (result) {
        var scr = document.getElementById('screen_post_link_'+id);
        var unscr = document.getElementById('unscreen_post_link_'+id);
        if (to_screen) {
            scr.style.display = 'none';
            unscr.style.display = '';
        } else {
            scr.style.display = '';
            unscr.style.display = 'none';
        }
    }
}

function screen_post(id, to_screen) {
    perl_screen_post(id, to_screen, screen_post_callback);
}

function cfm(obj) {
    if (typeof(PerlVar_Extlinks_Alert)!='undefined' && PerlVar_Extlinks_Alert==0) return true;
    var txt = obj.href;
    txt = txt.replace(/http:\/\/([A-Za-z0-9_\-\.]+)[^>]*/ig , "$1");
    return confirm('Вы собираетесь перейти по внешней ссылке на сайт: "'+txt+'"\n\nАдминистрация компании Mail.ru не несет ответственности за содержимое сайта "'+txt+'" и настоятельно рекомендует никогда не вводить пароль от своего почтового ящика на посторонних ресурсах. \n\nОткрыть сайт?');
}

function cfmu(url) {
    if (typeof(PerlVar_Extlinks_Alert)!='undefined' && PerlVar_Extlinks_Alert==0) return true;
    return confirm('Вы собираетесь перейти по внешней ссылке на сайт: "'+url+'"\n\nАдминистрация компании Mail.ru не несет ответственности за содержимое сайта "'+url+'" и настоятельно рекомендует никогда не вводить пароль от своего почтового ящика на посторонних ресурсах. \n\nОткрыть сайт?');
}

// dont use this, use getElemPos
function _getOffsetPosition(el) {
    el = $(el);
    if (!el) return;

    var width = el.offsetWidth, height = el.offsetHeight;
    var left = 0, top = 0;
    while (el) {
        left += el.offsetLeft;
        top += el.offsetTop;
        el = el.offsetParent;
    }

    return { 'left': left, 'top': top, 'width': width, 'height': height };
}

// dont use this, use getElemPos
function _getBoundingRectPosition(el) {
    el = $(el);
    if (!el || !el.getBoundingClientRect) return;

    var box = el.getBoundingClientRect();

    var body = document.body;
    var docElem = document.documentElement;

    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
 
    var clientTop = docElem.clientTop || body.clientTop || 0;
    var clientLeft = docElem.clientLeft || body.clientLeft || 0;
 
    var top  = box.top +  scrollTop - clientTop;
    var left = box.left + scrollLeft - clientLeft;

    var width = el.offsetWidth, height = el.offsetHeight;
    return { top: parseInt(top), left: parseInt(left), 'width': width, 'height': height };
}

function getElementPosition(el) {
    el = $(el);
    if (!el) return;

    var saved_props = ['display','visibility','position','top','left'], save = {};
    if (el.style.display == 'none') {
        var len = saved_props.length;
        while (len--) {
            var prop = saved_props[len];
            save[prop] = el.style[prop];
        }
        el.style.visibility = 'hidden';
        el.style.position = 'absolute';
        el.style.top = el.style.left = '-1000px';
        el.style.display = '';
    }

    var position;
    if (el.getBoundingClientRect) {
        position = _getBoundingRectPosition(el);
    } else {
        position = _getOffsetPosition(el);
    }

    if (save[saved_props[0]]) {
        var len = saved_props.length;
        while (len--) {
            var prop = saved_props[len];
            el.style[prop] = save[prop];
        }
    }

    return position;
}
function getElemPos(el) { return getElementPosition(el) }

function setAlpha(obj, alpha) {
    alpha = parseInt(alpha)
    alpha = (alpha > 100) ? 100 : (alpha < 1 ? 0 : alpha);
    if (document.body.filters) {
        if (isIE8 /*typeof obj.style.MsFilter != 'undefined'*/) {
            if (obj.filters.item('DXImageTransform.Microsoft.Alpha')) {
                obj.filters.item('DXImageTransform.Microsoft.Alpha').opacity = alpha;
            } else if (obj.style.MsFilter) {
                obj.style.MsFilter = obj.style.MsFilter.replace(/"$/, ' progid:DXImageTransform.Microsoft.Alpha(opacity=' + alpha + ')"');
            } else {
                obj.style.MsFilter = '"progid:DXImageTransform.Microsoft.Alpha(opacity=' + alpha + ')"';
            }
        }
        if (obj.filters.item('DXImageTransform.Microsoft.Alpha')) {
            obj.filters.item('DXImageTransform.Microsoft.Alpha').opacity = alpha;
        } else if (obj.style.filter) {
            obj.style.filter += ' progid:DXImageTransform.Microsoft.Alpha(opacity=' + alpha + ')';
        } else {
            obj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + alpha + ')';
        }
    } else {
        obj.style.opacity = alpha/100;
    }
}

function setPngBg(elem, src) {
    if (document.body.filters && !src.indexOf('iepng')) {
        elem.style.backgroundImage = 'url(http://img.mail.ru/0.gif)';
        elem.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
    } else {
        elem.style.backgroundImage = 'url(' + src + ')';
    }
}

function getMousePos(event) {
    var docElement = document.documentElement,
        body = document.body || { scrollLeft: 0, scrollTop: 0 };
    return {
        x: parseInt( event.pageX || (event.clientX +
            (docElement.scrollLeft || body.scrollLeft) -
            (docElement.clientLeft || 0)) ),
        y: parseInt( event.pageY || (event.clientY +
            (docElement.scrollTop || body.scrollTop) -
            (docElement.clientTop || 0)) )
    };
}

function cancelEvent(event) {
    event.cancelBubble = true;
    event.returnValue = false;
    if (event.stopPropagation) event.stopPropagation();
    if (event.preventDefault) event.preventDefault();
}

function getClientWidth() {
    return (document.compatMode=='CSS1Compat' && !window.opera) ? document.documentElement.clientWidth : document.body.clientWidth;
}
function getViewportWidth() { return getClientWidth() }

function getClientHeight() {
    return Math.min(
        (document.documentElement ? parseInt(document.documentElement.clientHeight) : 0),
        (document.body ? parseInt(document.body.clientHeight) : 0)
    );
}
function getViewportHeight() { return getClientHeight() }

function getBodyScrollTop() {
    return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}

function getBodyScrollLeft() {
    return self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft);
}

function getBodyScrollHeight() { return document.body.scrollHeight }

function getBodyScrollWidth() {
    return Math.max(
        (document.documentElement ? parseInt(document.documentElement.scrollWidth) : 0),
        document.body.scrollWidth
    );
}

function shadowDiv(key, color){
    var shad = gebi('shadow_div');
    if (!color) color = '#333';
    if (key == '1') {
        shad.style.backgroundColor = color;
        shad.style.height = document.body.scrollHeight;
        shad.style.display= '';
    } else {
        shad.style.display= 'none';
    }
}

function addCssClass(elem, classname) {
    elem = $(elem);
    var re = new RegExp('\\b'+classname+'\\b', 'i');
    if ( re.test(elem.className) ) return;
    elem.className = elem.className + ' ' + classname;
}
function removeCssClass(elem, classname) {
    elem = $(elem);
    var re = new RegExp('\\s*\\b'+classname+'\\b\\s*', 'i');
    elem.className = elem.className.replace(re, ' ');
}

function setSelectValue(select, value) {
    var len = select.options.length;
    while (len--) {
        var option = select.options[len];
        if (option.value == value) {
            select.selectedIndex = len;
            break;
        }
    }
}

function getSelectValue(select) {
    return select.value;
}

function setRadioValue(radio, value) {
    var len = radio.length;
    if (len == undefined) {
        radio.checked = (radio.value == value.toString());
        return;
    }
    for (var i = 0; i < len; i++) {
        radio[i].checked = false;
        if (radio[i].value == value.toString()) {
            radio[i].checked = true;
        }
    }
}

function getRadioValue(radio) {
    var len = radio.length;
    if (len == undefined) {
        if (radio.checked) {
            return radio.value;
        } else {
            return '';
        }
    }
    for (var i = 0; i < len; i++) {
        if (radio[i].checked) {
            return radio[i].value;
        }
    }
    return '';
}

function rgbToHex(c) {
    if (!c.match(/rgb/ig)) return c; // если не нужно преобразовыавть
    var c, s, i, h = '', x='0123456789ABCDEF';
    if (c) {
        c = c.replace(/rgb\(/ig,'');
        c = c.replace(/\)/ig,'');
        s = c.split(',');

        for (i=0; i < 3; i++) {
            n = parseInt(s[i]);
            h += x.charAt(parseInt(n/16)) + x.charAt(n%16);
        }
        return '#'+h;
    } else {
        return false;
    }
}



if (document.addEventListener) {
    function addHandler(object, eventName, handler) {
        var name = getDOMEventName(eventName);
        object.addEventListener(name, handler, false);
    }
} else if (document.attachEvent) {
    function addHandler(object, eventName, handler) {
        var name = getDOMEventName(eventName);
        object.attachEvent('on' + name, handler);
    }
}

if (document.removeEventListener) {
    function removeHandler(object, eventName, handler) {
        var name = getDOMEventName(eventName);
        object.removeEventListener(name, handler, false);
    }
} else if (document.detachEvent) {
    function removeHandler(object, eventName, handler) {
        var name = getDOMEventName(eventName);
        object.detachEvent('on' + name, handler);
    }
}

function getDOMEventName(eventName) {
  if (eventName && eventName.indexOf(':') != -1) return 'dataavailable';
  return eventName;
}

// dom:loaded, derived from prototype.js
function fire(element, eventName, memo) {
  element = $(element);
  if (element == document && document.createEvent && !element.dispatchEvent)
    element = document.documentElement;

  var event, name = getDOMEventName(eventName);
  if (document.createEvent) {
    event = document.createEvent('HTMLEvents');
    event.initEvent(name, true, true);
  } else {
    event = document.createEventObject();
    event.eventType = 'on' + name;
  }

  event.eventName = eventName;
  event.memo = memo || {};

  if (document.createEvent) {
    element.dispatchEvent(event);
  } else {
    element.fireEvent(event.eventType, event);
  }

  return event;
}

(function() {
  /* Support for the DOMContentLoaded event is based on work by Dan Webb,
     Matthias Miller, Dean Edwards and John Resig. */

  var timer;

  function fireContentLoadedEvent() {
    if (document.loaded) return;
    if (timer) window.clearInterval(timer);
    fire(document, 'dom:loaded');
    document.loaded = true;
  }

  if (document.addEventListener) {
    if (navigator.userAgent.indexOf('AppleWebKit/') > -1) {
      timer = window.setInterval(function() {
        if (/loaded|complete/.test(document.readyState))
          fireContentLoadedEvent();
      }, 0);

      addHandler(window, 'load', fireContentLoadedEvent);

    } else {
      document.addEventListener('DOMContentLoaded', fireContentLoadedEvent, false);
    }

  } else {
    // http://dean.edwards.name/weblog/2006/06/again/#comment335794
    if (document.body) {
      try {
        document.documentElement.doScroll('left');
        fireContentLoadedEvent();
      } catch(e) {}
    }
    if (!document.loaded) setTimeout(arguments.callee, 50);
  }
})();
