function showhide(id)
{
    var e=document.getElementById(id);
    if(e) {
        if(e.style.display=='none') {
            e.style.display='block';
            return 'block';
        }
        else e.style.display='none';
        return 'none';
    }
}

function show(id)
{
    byid(id).style.display='block';
}

function hide(id)
{
    byid(id).style.display='none';
}

function showAuthForm(id, to_id) {
    SetTopAndRight(id, to_id);
    showhide(to_id);
    return false;
}

function encodeStringForMail(s)
{
	var letters = "абвгдеёжзийклмнопрстуфхцчшщьыъэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯ";
	var codes = [
					0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xB8, 0xE6, 0xE7, 0xE8, 0xE9,
					0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4,
					0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFC, 0xFB, 0xFA, 0xFD, 0xFE, 0xFF,
					0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xA8, 0xC6, 0xC7, 0xC8, 0xC9,
					0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4,
					0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDC, 0xDB, 0xDA, 0xDD, 0xDE, 0xDF
				];
			
	for (var i=0; i < codes.length; i++) {
		s = s.replace(new RegExp(letters.charAt(i), "g"), "%"+codes[i].toString(16));
	}
	return s;
}

function getServerName() {
	var str = window.location.protocol + '//' + window.location.host + window.location.pathname;
	str = str.substr(0, str.lastIndexOf('/')+1);
	return str;
}
			
function isdefined(variable) {
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function escapeMe(str) {
    // Инициализируем таблицу перевода
    var trans = [];
    for (var i = 0x410; i <= 0x44F; i++)
      trans[i] = i - 0x350; // А-Яа-я
    trans[0x401] = 0xA8;    // Ё
    trans[0x451] = 0xB8;    // ё

    // Сохраняем стандартную функцию escape()
    var escapeOrig = window.escape;

    // Переопределяем функцию escape()
    escape_me = function(str)
    {
      var ret = [];
      // Составляем массив кодов символов, попутно переводим кириллицу
      for (var i = 0; i < str.length; i++)
      {
        var n = str.charCodeAt(i);
        if (typeof trans[n] != 'undefined')
          n = trans[n];
        if (n <= 0xFF)
          ret.push(n);
      }
      return escapeOrig(String.fromCharCode.apply(null, ret));
    }
    return escape_me(str);
}

function win2unicode(str)
{
    var charmap   = unescape(
      "%u0402%u0403%u201A%u0453%u201E%u2026%u2020%u2021%u20AC%u2030%u0409%u2039%u040A%u040C%u040B%u040F"+
      "%u0452%u2018%u2019%u201C%u201D%u2022%u2013%u2014%u0000%u2122%u0459%u203A%u045A%u045C%u045B%u045F"+
      "%u00A0%u040E%u045E%u0408%u00A4%u0490%u00A6%u00A7%u0401%u00A9%u0404%u00AB%u00AC%u00AD%u00AE%u0407"+
      "%u00B0%u00B1%u0406%u0456%u0491%u00B5%u00B6%u00B7%u0451%u2116%u0454%u00BB%u0458%u0405%u0455%u0457")
    var code2char = function(code) {
               if(code >= 0xC0 && code <= 0xFF) return String.fromCharCode(code - 0xC0 + 0x0410)
               if(code >= 0x80 && code <= 0xBF) return charmap.charAt(code - 0x80)
               return String.fromCharCode(code)
            }
    var res = ""
    for(var i = 0; i < str.length; i++) res = res + code2char(str.charCodeAt(i))
    return res
}
var userAgent = navigator.userAgent.toLowerCase();
var browser = {
    version: (userAgent.match( /.+(?:rv|it|ra|ie|me|firefox)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
    mversion: (userAgent.match( /\ V|version\/([\d\.]+)\ / ) || [0, '0'])[1],
    chrome: /chrome/.test( userAgent ),
    safari: /webkit/.test( userAgent ) && !/(chrome)/.test( userAgent ),
    opera: /opera/.test( userAgent ),
    msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
    mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

function debug( elem, type )
{
    if(typeof fdebug=='undefined' || fdebug<1) return;
    var dbg = byid('debug');
    if(typeof dbg.type=='undefined') dbg.type = 1;
    else dbg.type++;
    var html = dbg.innerHTML;
    if( typeof type=='undefined' ) {
        html += dbg.type+':';
        for(var ii in elem) {
            try {
                html += '<b>'+ii+':</b>'+elem[ii]+'<br/>';
            }catch(err) {
                html += '<b>'+ii+':</b>'+err+'<br/>';
            }
        }
    }else {
        html += dbg.type+':'+elem+'<br/>';
    }
    dbg.innerHTML = html;
    dbg.scrollTop = dbg.scrollHeight;
}

function loginAjax(url, fname)
{
    var Fm = document.forms[fname];
    if(Fm) {
        var login = Fm.elements['login'].value.replace(/<>&/g,'').replace(/^\s+|\s+$/,'');
        var pwd = Fm.elements['password'].value.replace(/<>&/g,'').replace(/^\s+|\s+$/,'');
        if(typeof Fm.elements['realmname']!='undefined') var rlmn = Fm.elements['realmname'].value.replace(/<>&/g,'').replace(/^\s+|\s+$/,'');
        else var rlmn = '';
        var rem = Fm.elements['remember_auth'].checked ? 1 : 0;
        if(login!='' && pwd!='') {
            byid('login-error').innerHTML = '';
            sendRequest(url, 'ajax=1&login='+login+'&password='+pwd+'&realmname='+rlmn+'&rem='+rem,{},respLogin,true);
        }else {
            byid('login-error').innerHTML = _('incorrect login or password');
        }
    }
    return false;
}

function respLogin(res, e)
{
    //debug(res.firstChild.childNodes);
    if(isset(res.firstChild.childNodes[0])) {
        var result = res.firstChild.childNodes[0].data;
        
        if(result!='' && result!='0') {
            if(result==1) {
                Delete_Cookie('conference-remember-auth', '/');
                Delete_Cookie('auth_key', '/');
            }else{
                Set_Cookie('conference-remember-auth', 1, 365, '/');
                Set_Cookie('auth_key', result, 365, '/');
            }
            if(window.location.href.indexOf('registration/')!=-1) {
                window.location.href = service_url+'appointment/';
            }else{
                window.location.href = window.location.href.replace(/\#.*/,'');
            }
        }else{
            byid('login-error').innerHTML = _('incorrect login or password');
        }
    }
}

function sendUserEvents(event, data)
{
    if(g_UEvents>0) {
        var userAgent = navigator.userAgent.toLowerCase();
        var e = {'event': event};
        var ps = event=='info'?'&agent='+userAgent+'&ver='+g_WMO.Version+'&os='+user_os:'';
        sendRequest(service_url+'user_event/', 'ajax=1&event='+event+'&login='+user.login+'&name='+user.name+ps+'&data='+data.toString()+'&jid='+conf.confid+"@"+user.domain,e,responseUserEvents,true);
    }
}

function responseUserEvents(res,e)
{
    try{
        result = res.documentElement.getElementsByTagName('result')[0].firstChild.data;
    }catch(e){}
}

function checkEmail(id)
{
    var e = byid(id);
    if( e.value=='' || (!/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(e.value)) ) {
        byid('error').innerHTML = _('email not valid');
        return false;
    }else return true;
}

function checkPass(id)
{
    var e = byid(id), e2 = byid(id+'2');
    if( e.value=='' || (e.value!=e2.value) ) {
        byid('error').innerHTML = _('password empty or not equal');
        return false;
    }else return true;
}

function getLetterByClient(e)
{
    var c = byid('confid');
    if(e.value!='') {
        sendRequest(service_url+'appointment/', 'ajax=1&id='+c.value+'&client='+e.value,e,respLetterClient,true);
        e.options[0].selected = true;
    }
}

function getLetterByClientJQ(e, trans)
{
    var c = byid('confid');
    if(e.value!='') {
        sendJRequest(service_url+'appointment/', {action: 'mailconf', id: c.value, client: e.value});
        if(trans) sendJRequest(service_url+'appointment/', {action: 'mailtrans', id: c.value, client: e.value});
        e.options[0].selected = true;
    }
}

function respLetterClient(r, e)
{
    if(r.firstChild.childNodes[0]) {        
        if(browser.opera) {
            var eo = byid('opera_mailto_fix');
            var a = document.createElement('a');
            a.href = r.firstChild.childNodes[0].data;
            a.innerHTML = _('click to open letter');
            eo.innerHTML = '';
            eo.appendChild(a);
        }
        window.location.href = r.firstChild.childNodes[0].data.toString();
    }
}

function sendLetterClient(mail)
{
    if(browser.opera) {
        var eo = byid('opera_mailto_fix');
        var a = document.createElement('a');
        a.href = mail;
        a.innerHTML = _('click to open letter');
        eo.innerHTML = '';
        eo.appendChild(a);
    }
    window.location.href = mail;
}

var html_getflashplayer = '<a href="http://www.adobe.com/go/getflashplayer" target="_blank"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a>';
function addSWF(src, contentid, swfid, w, h, fv, ps, atts)
{
    byid(contentid).innerHTML = '<div id="'+swfid+'"></div>';
    if(swfobject.getFlashPlayerVersion().major<9) {
        byid(contentid).innerHTML = _('install flashplayer {1}',html_getflashplayer);
        return false;
    }
    var flashvars = typeof fv=='undefined'?{}:fv;
    var params = typeof ps=='undefined'?{}:ps;
    var attributes = typeof atts=='undefined'?{}:atts;
    swfobject.embedSWF(src, swfid, w, h, "9.0.0", "", flashvars, params, attributes);
    return true;
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

function sendRequest(url,dattt,object,p_callback,return_xml,met) {
   var http_request = false;
   if(typeof met=='undefined') var met = 'post';
    if (window.XMLHttpRequest) { // Mozilla, Safari, Others..
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
    http_request.onreadystatechange = function() {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                if (return_xml) {
                    p_callback(http_request.responseXML,object);
                } else {
                    p_callback(http_request.responseText,object);
                }
            } else {
                p_callback(false,object);
                //http_request.requestHandler(http_request.status);
                return 404;
            }
        }
    }
    try {
        http_request.open(met, url, true);
        http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        http_request.send(dattt);
    }catch(e){}

}

function sendJRequest(url, param, rfunc, errfunc)
{
    url = url ? url : window.location.href;    
    url = url.replace(/(#.*)/, '');
    
    params = {params: "undefined" != param ? toQueryString(param) : "", ajax: 1};
    $(document).ready(function(){
        if(typeof rfunc=='function') var r = $.post(url, params, rfunc, 'JSON');
        else var r = $.post(url, params, parseResponse, 'JSON');
        if(typeof errfunc=='function' && !browser.msie) r.onerror = function(){ errfunc();};
        //else r.onerror = function(){ parseError();};
    });
}

function toQueryString(object)
{
    var key, chk = 0, ret = '';
    for(key in object) {
        var values = encodeURIComponent(object[key]);
        if(chk) ret += '&';
        ret += key+'='+values;
        chk = 1;
    }
    return ret;
}

function parseResponse(transport, json)
{
    var response = $.evalJSON(transport);
    
    if(response.div_arr) {
        for(ii in response.div_arr) {
            if(ii==parseInt(ii)) {
                var div_id = document.getElementById(response.div_arr[ii]['id']);
                if(div_id) {
                    div_id.innerHTML = response.div_arr[ii]['content'];
                    if(response.div_arr[ii]['content']!='') {
                        div_id.style.display = 'block';
                        div_id.type = 1;
                    }
                }
            }
        }
    }
    if(response.div_id)
    {
        var e=document.getElementById(response.div_id);
        if(e) e.innerHTML = response.div_content;
        //$(response.div_id).style.display = 'block';
    }
    if(response.js_code)
    {
        //alert(response.js_code);
        try{eval(response.js_code);} 
        catch(err) 
        {
            //alert("Inline script error " + err.name + ": " + err.message + "|"+err.line);
        }
    }
    clearLoader();
}

function parseError()
{}

function _(t){
    if(typeof lang[t]!='undefined') {
        if(arguments.length>1) {
            str = 'sprintf(\''+lang[t]+'\'';
            for(var i=1;i<arguments.length;i++){
                str += ',\''+arguments[i]+'\'';
            }
            str += ')';
            return eval(str);
        }else{
            return lang[t];
        }
    }
    return t;
}

function sprintf(){
    var num = arguments.length;
    var oStr = arguments[0];
    for (var i = 1; i < num; i++) {
        var pattern = "\\{" + (i) + "\\}";
        var re = new RegExp(pattern, "g");
        oStr = oStr.replace(re, arguments[i]);
    }
    return oStr;
}

function getTimer() {var dt = new Date();return dt.getTime();}
function getTimerInfo()
{
    var ret = '';
    for(var i=1;i<timer_init.length-1;i++){
        ret += '<b>'+timer_init[i][0]+'</b>:'+parseInt(timer_init[i+1][1] - timer_init[i][1])+'<br/>';
    }
    if(timer_init.length>2) {
    ret += '<b>'+timer_init[i][0]+'</b>: end<br/>';
    ret += '<b>Sum</b>:'+parseInt(timer_init[i][1] - timer_init[0][1])+'<br/>';
    }
    timer_init = new Array();
    return ret;
}
function isset(o) {return (typeof o!='undefined' && o!=null);}
function byid(id){return document.getElementById(id);}
function in_array(val, arr, key){
    for(var i in arr) if(arr[i]==val) return (typeof key!='undefined')?i:true;
    return false;
}
Array.prototype.remove = function(index) {
    if(this.length>1) {
        for (var i = index-0; i < this.length; i++)
            this[i] = this[i+1];
    }
    this.pop();
};
function addClass(e, cname)
{
    if(typeof e=='string') e=byid(e);
    if(e.className=='') e.className = cname;
    else if( e.className!=cname && !e.className.match(new RegExp('\\ '+cname+'\$')|new RegExp('\^'+cname+'\\ ')|new RegExp(' '+cname+' ')) ) e.className += ' '+cname;
}
function removeClass(e, cname)
{
    if(typeof e=='string') e=byid(e);
    if(e.className==cname) e.className = '';
    else if(e.className.indexOf(cname)>-1) e.className = e.className.replace(new RegExp('\^'+cname+'\\ ')|new RegExp('\\ '+cname+'\$')|new RegExp(' '+cname+' '), '');
}
function Arr2Str(n, a) {
    if(typeof a=='string') return "'"+n+"': '"+a.toString().replace(/[\n]+/g,' ').replace(/[\ ]+/g, ' ')+"'";
    var s=[];
    for(var i=0;i<a.length;i++) {
        if(typeof a[i]=='string' || typeof a[i]=='number') s.push("'"+i+"':'"+a[i].toString().replace(/[\n]+/g,' ').replace(/[\ ]+/g, ' ')+"'");
        else if(typeof a[i]=='array') s.push(Arr2Str(i,a[i]));
        else if(typeof a[i]=='object') s.push(Obj2Str(i,a[i]));
    }
    return "'"+n+"':["+s.slice(',')+']';
}
function Obj2Str(n, o) {
    if(typeof o=='string') return "'"+n+"': '"+o.toString().replace(/[\n]+/g,' ').replace(/[\ ]+/g, ' ')+"'";
    var s=[];
    for(var i in o) {
        if(typeof o[i]=='string' || typeof o[i]=='number') s.push("'"+i+"':'"+o[i].toString().replace(/[\n]+/g,' ').replace(/[\ ]+/g, ' ')+"'");
        else if(typeof o[i]=='object') s.push(Obj2Str(i,o[i]));
        else if(typeof o[i]=='array') s.push(Arr2Str(i,o[i]));
    }
    return "'"+n+"':{"+s.slice(',')+'}';
}

function SetTopAndCenter(id,to_id)
{
    var x=$("#"+id).offset().left+$("#"+id).width()/2-$("#"+to_id).width()/2;
    var y=$("#"+id).offset().top+$("#"+id).height()/2-$("#"+to_id).height()/2;
    $("#"+to_id).css({left:x,top:y});
}

function SetTopAndRight(id,to_id)
{
    var x=$("#"+id).offset().left+$("#"+id).width()-$("#"+to_id).width();
    var y=$("#"+id).offset().top;
    $("#"+to_id).css({left:x,top:y});
}

function setTopLeft(destid, toid)
{
    if(typeof destid=='object') {
        var x=$(destid).offset().left;
        var y=$(destid).offset().top;
    }else{
        var x=$("#"+destid).offset().left;
        var y=$("#"+destid).offset().top;
    }
    $("#"+toid).css({left:x,top:y});
}

function setTopRight(destid, toid)
{
    if(typeof destid=='object') {
        var x=$(destid).offset().left+$(destid).width()+20;
        var y=$(destid).offset().top;
    }else{
        var x=$("#"+destid).offset().left+$("#"+destid).width()+20;
        var y=$("#"+destid).offset().top;
    }
    $("#"+toid).css({left:x,top:y});
}

function setTopARight(destid, toid)
{
    if(typeof destid=='object') {
        var x=$(destid).offset().left+$(destid).width()-$("#"+toid).width();
        var y=$(destid).offset().top;
    }else{
        var x=$("#"+destid).offset().left+$("#"+destid).width()-$("#"+toid).width();
        var y=$("#"+destid).offset().top;
    }
    $("#"+toid).css({left:x,top:y});
}

function loader(elem)
{
    var l=byid('loader');
    if(l==null) {
        var l = document.createElement('span');
        l.id = 'loader';
        l.style.display = 'none';
        l.innerHTML = '<img src="'+service_url+'i/ajax-loader.gif" width="16" height="16" />';
        document.body.insertBefore(l, document.body.firstChild);
    }
    setTopRight(elem, l.id);
    l.style.display = 'block';
}

function clearLoader()
{
    var l=byid('loader');
    if(l!=null) l.style.display='none';
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires )
    {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 )
            {
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
    if ( Get_Cookie( name ) ) document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}			

