function showhide(id)
{
    var e=document.getElementById(id);
    if(e) {
        if(e.style.display=='none')e.style.display='block';
        else e.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
}

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;
}

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+$/,'');
        var rem = Fm.elements['remember_auth'].checked ? 1 : 0;
        if(login!='' && pwd!='') {
            byid('login-error').innerHTML = '';
            sendRequest(url, 'ajax=1&login='+login+'&password='+pwd+'&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 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,{},respLetterClient,true);
        e.options[0].selected = true;
    }
}

function respLetterClient(r, e)
{
    if(r.firstChild.childNodes[0]) {
        window.location.href = r.firstChild.childNodes[0].data;
    }
}

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 {
                return 404;
                object.requestHandler(http_request.status);
            }
        }
    }
    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 _(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/>';
    }
    ret += '<b>'+timer_init[i][0]+'</b>: end<br/>';
    ret += '<b>Sum</b>:'+parseInt(timer_init[i][1] - timer_init[0][1])+'<br/>';
    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;
}

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 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";
}			
