var MouseX = 0, MouseY = 0;

var str = '';

document.onmousemove = function(event){
    if (typeof event == 'undefined')
    {
        event = window.event;
    }
    if (event.clientX)
    {
        var bd = document.documentElement
            ? document.documentElement
            : document.body;
        MouseX = (event.clientX + bd.scrollLeft);
        MouseY = (event.clientY + bd.scrollTop);
    }
    else
    {
        MouseX = event.pageX;
        MouseY = event.pageY;
    }
}

function d2h(d) {return d.toString(16);}

function h2d(h) {return parseInt(h, 16);}

function d2b(d) {return d.toString(2);}

function b2d(b) {return parseInt(b, 2);}

function trim(str)
{
    str = new String(str);
    return str.replace(/^\s+|\s+$/g,"");
}
function ltrim(str)
{
    return str.replace(/^\s+/,"");
}
function rtrim(str)
{
    return str.replace(/\s+$/,"");
}

function photopage(classname, id, imgfrom, imgto, imgcur) {

    var url = '../ajax/images.php';
    var pars = 'classname='+classname+'&id='+id+'&imgfrom='+imgfrom+'&imgto='+imgto+'&imgcur='+imgcur;

    var myAjax = new Ajax.Request(
        url,
        {method: 'get', parameters: pars, onFailure: reportError, onComplete: function(r){restoreimages(r)}});

    return false;
}

function restoreimages (r) {
    var ret=r.responseText;
    var imagesnav=$("imagesnav");
    imagesnav.innerHTML=ret;
}

function photoset (classname, id, imgcur) {

    var url = '../ajax/imageplace.php';
    var pars = 'classname='+classname+'&id='+id+'&imgcur='+imgcur;

    var myAjax = new Ajax.Request(
        url,
        {method: 'get', parameters: pars, onFailure: reportError, onComplete: function(r){restoreimageplace(r)}});

    return false;
}

function restoreimageplace(r) {
    var ret=r.responseText;
    var imagesnav=$("imageplace");
    imagesnav.innerHTML=ret;
}

function reportError(request) {
    alert('Sorry. There was an error.');
}

function myshow(field, id) {

    var reshow=1;
    if (show_desc) {
        if (show_desc==id) var reshow=0;
    }

    if (reshow) {
        var posy=getPosition(field)[1];
        var posx=getPosition(field)[0];
        var div=$(id);
        div.style.position="absolute";
        div.style.top=eval(posy-20)+"px";
        div.style.left=eval(posx-20)+"px";
        div.style.display="block";
        show_desc=id;
    }
}

function myhide(id) {
    var div=$(id);
    div.style.display="none";
    show_desc=0;
}

function getPosition(obj) {
    var o=obj;
    var x=0, y=0;
    while(o) {
        x+=o.offsetLeft;
        y+=o.offsetTop;
        o=o.offsetParent;
    }
    return [x,y];
}

var win;
function big_photo(f,w,h) {
    if (win) {
        win.close();
    }

    win=window.open('../photo.php?f='+f, null, "width="+w+",height="+h+",toolbar=0,scrollbars=no,resizable=no");
    return false;
}

function viewImg(image_href){
      var xstr = 'scrollbars=no,toolbar=no,status=no,menubar=no,directories=no,location=no,resizable=yes,width=160,height=160';
      var prodWindow = window.open(image_href, 'window'+Math.round(Math.random()*1000), xstr);
      if (prodWindow) prodWindow.focus();
}

function backToSite(){
    var prodWindow = window.opener;
    if (prodWindow){
        prodWindow.focus();
        window.close();
    }
}

function housePrew(url, dir_image, image_name){
    var house_prev = document.getElementById('house');
    house_prev.innerHTML = '<a href="/view_img.php?dir_image=' +
         dir_image + '&amp;image_name=' + image_name +
         '" target="_blank" onclick="viewImg(this.href); return false;"><img src="' +
         url + dir_image + '/medium/' + image_name + '" alt="" /></a>';
}

var popupWindow = null;

function popup(wName, url, width, height, options)
{
    var iLeft = ( screen.availWidth  - width ) / 2 ;
    var iTop  = ( screen.availHeight - height ) / 2 ;

    var sOptions = {};
    if (options)
    {
        sOptions.toolbar = options.toolbar || 'no';
        sOptions.status  = options.status || 'no';
        sOptions.resizable = options.resizable || 'no';
        sOptions.dependent = options.dependent || 'yes';
        sOptions.scrollbars = options.scrollbars || 'no';
    }
    sOptions.width  = width;
    sOptions.height = height;
    sOptions.left   = iLeft;
    sOptions.top    = iTop;

    var wOptions = '';
    for (var x in sOptions)
    {
        if (wOptions != '')
        {
            wOptions += ',';
        }
        wOptions += x + '=' + sOptions[x];
    }

    var isOpera = !!window.opera;

    try
    {
        if (popupWindow)
        {
            popupWindow.close();
        }
    }
    catch(e){/* Handle opera bug */}


    var isMSIE = /*@cc_on!@*/false;
    if ( isMSIE )
    {
        // The following change has been made otherwise IE will open the file
        // browser on a different server session (on some cases):
        // http://support.microsoft.com/default.aspx?scid=kb;en-us;831678
        // by Simone Chiaretta.
        popupWindow = window.open(url, wName, wOptions) ;

        if ( popupWindow )
        {
            // Detect Yahoo popup blocker.
            try
            {
                var sTest = popupWindow.name ; // Yahoo returns "something",
                // but we can't access it, so detect that and avoid strange errors for the user.
                popupWindow.opener = window ;
            }
            catch(e)
            {
                alert("The resources browser could not be opened. Make sure that" +
                        " all popup blockers are disabled.") ;
            }
        }
        else
            alert("The resources browser could not be opened. Make sure that all" +
                    " popup blockers are disabled.") ;
    }
    else
        popupWindow = window.open(url, wName, wOptions);
}

function featureMapPopup(idFeature)
{
    popup('FeatureMap', '/dialog/map.php?id=' + idFeature, 950, 570);
}

function photoPopup(idSurface)
{
    popup('SurfacePhotoMap', '/dialog/photo.php?id=' + idSurface, 660, 550);
}

function cInfoPopup(idConstruction)
{
    var url = '/dialog/info.php?';
    url += 'id=' + idConstruction;
    url += '&year=' + $('year').value;
    url += '&month=' + $('month').value;
    popup('ConstructionInfo', url, 670, 550, {scrollbars : 'yes'});
}

function mInfoPopup(idConstruction)
{
    var url = '/dialog/info.php?';
    url += 'id=' + idConstruction;
    url += '&year=' + $('year').value;
    url += '&month=' + $('month').value;
    popup('ConstructionInfo', url, 670, 550, {scrollbars : 'yes'});

    $A($$('.map-pin.selected')).each(function(item){$(item).removeClassName('selected')});
    var element = $('dm' + idConstruction);
    if (element != null)
    {
        element.addClassName('selected');
        mapDM.selected = element.id;
    }
    return false;
}

function schemePopup(href)
{
    popup('ContactScheme', href, 820, 525);
}


function mode(radio)
{
    switch (radio.value)
    {
        case "1":
            location.href = '/ap.html';
            break;

        case "2":
            location.href = '/aap.html';
            break;

        case "3":
            location.href = '/map.html';
            break;

        case "4":
            location.href = '/kap.html';
            break;

        default:
            location.href = '/ap.html';
            break;
    }
}

function selectOption(select, value)
{
    var opts = $(select).options;
    for (var i = 0; i < opts.length; i++)
    {
        opts[i].selected = false;
        if ( opts[i].value == value )
        {
            opts[i].selected = true;
        }
    }
}

function select_innerHTML(objeto,innerHTML)
{
    objeto.innerHTML = ""
    var selTemp = document.createElement("select")
    var opt;
    selTemp.id = "micoxselect1"
    document.body.appendChild(selTemp)
    selTemp = document.getElementById("micoxselect1")
    selTemp.style.display="none"
    if(innerHTML.toLowerCase().indexOf("<option")<0)
    {
        innerHTML = "<option>" + innerHTML + "</option>"
    }
    innerHTML = innerHTML.replace(/<option/gi,"<span").replace(/<\/option/gi,"</span")
    selTemp.innerHTML = innerHTML


    for(var i = 0; i < selTemp.childNodes.length; i++)
    {
          var spantemp = selTemp.childNodes[i];
        if(spantemp.tagName)
        {
            opt = document.createElement("OPTION")
               if(document.all)
               { //IE
                objeto.add(opt)
               }
               else
               {
                objeto.appendChild(opt)
               }

               //getting attributes
               for(var j = 0; j < spantemp.attributes.length ; j++)
               {
                var attrName = spantemp.attributes[j].nodeName;
                var attrVal = spantemp.attributes[j].nodeValue;
                if(attrVal)
                {
                     try
                     {
                          opt.setAttribute(attrName,attrVal);
                          opt.setAttributeNode(spantemp.attributes[j].cloneNode(true));
                     }
                     catch(e){}
                }
               }
               //getting styles
               if(spantemp.style)
               {
                for(var y in spantemp.style)
                {
                     try
                     {
                         opt.style[y] = spantemp.style[y];
                     }
                     catch(e){}
                }
               }
               //value and text
               opt.value = spantemp.getAttribute("value")
               opt.text = spantemp.innerHTML
               //IE
               opt.selected = spantemp.getAttribute('selected');
               opt.className = spantemp.className;
          }
     }
     document.body.removeChild(selTemp)
     selTemp = null
}

function toggleBit(number, bit)
{
    var mask = 1 << (bit - 1);
    var m = number & ~mask;
    var n = number & mask;
    return m | (n ^ mask);
}

function clearBit(number, bit)
{
    var mask = 1 << (bit - 1);
    return number & ~mask;
}

function setBit(number, bit)
{
    var mask = 1 << (bit - 1);
    return number | mask;
}

function isMouseLeaveOrEnter(e, handler)
{
    if (e.type != 'mouseout' && e.type != 'mouseover')
    {
        return false;
    }

    var reltg = e.relatedTarget != 'undefined'
                   ? e.relatedTarget
                   : e.type == 'mouseout'
                        ? e.toElement
                        : e.fromElement;
    while (reltg && reltg != handler)
    {
       reltg = reltg.parentNode;
    }
    return (reltg != handler);
}

function getRadioValue(radioName)
{
    var radio = $A(document.getElementsByName(radioName)).detect(function(e){
            if (e.type == 'radio')
            {
                return e.checked;
            }
            return false;
    });

    if (radio)
    {
        return radio.value;
    }
    else
    {
        return null;
    }
}

var loginWin = null;
var loginCallback = null;

function auth()
{
    if (loginWin === null) {
        loginWin = new Control.Modal(false, {
            contents: '',
            overlayCloseOnClick : false,
            fade: false
        });
    }
    loginWin.update('<div align="center"><img src="/style/tooltip-loader.gif"' +
        ' width="32" height="32" alt="загрузка"><br><b>Загрузка<\/b><\/div>');

    new Ajax.Request('/ajax/loginDialog.php',{
        method : 'get',

        onComplete: function (transport)
        {
            loginWin.update(transport.responseText);
            $A($$('div.login_win .form.field input')).each(function(item) {
                $(item).setStyle({'position' : 'fixed'});
            });
            login_focus();
        }
    });
    loginWin.showWin();

    if (Prototype.Browser.Gecko) {
        Control.Modal.container.setStyle({ position: 'fixed' });

    }
}

function login_focus()
{
    var login = $('login-name');
    if (login)
    {
        login.activate();
    }
    else
    {
        window.setTimeout(login_focus, 100);
    }
}

function login_close()
{
    if (loginWin)
    {
        loginWin.hideWin();
    }
}

function login_auth(callback)
{
    $('login-loader').style.visibility = 'visible';
    new Ajax.Request('/ajax/auth.php',
    {
            method : 'post',
            parameters : {
                'login'  : $('login-name').value,
                'password' : $('login-password').value
            },

            onComplete: function (transport)
            {
                $('login-loader').style.visibility = 'hidden';
                var response = eval('(' + transport.responseText + ')' );
                if (response.status == 'OK') {
                    var user_login = $('user-login');
                    if (user_login) {
                        var str = response.auth.UserLogin;
                        str += ' - <a href="logout.php" class="olmisoft">выход</a>';
                        user_login.update(str);
                    }

                    var reservation = $('reservation_menu_item');
                    if (reservation && response.reservation) {
                        reservation.show();
                    }

                    /*var campaign = $('campaign_menu_item');
                    if (campaign) {
                        campaign.show();
                    }*/

                    var idCustomer = $('idCustomer');
                    if (idCustomer) {
                        idCustomer.value = response.auth.idUser;
                    }
                    login_close();
                    if (typeof loginCallback == 'function') {
                        loginCallback();
                    }
                    loginCallback = null;
                } else {
                    $('login-error').update(response.message);
                }
            }
    });
}

var AjaxLoader = null;

try {

    var ajxCNT = [];

    function showLoader()
    {
        ajxCNT.push('1');
    //    $('test').insert('|' + ajxCNT.length + '>');
        if (ajxCNT.length <= 1) {
            AjaxLoader.showWin();
        }
    }

    function hideLoader()
    {
    //    $('test').insert('<' + ajxCNT.length + '|');
        if (ajxCNT.length <= 1) {
            AjaxLoader.hideWin();
        }
        ajxCNT.pop();
    }

    AjaxLoader = new Control.Modal(false,{
        width: 200,
        height: 130,
        overlayCloseOnClick: false,
        contents: '<div align="center"><img src="/img/ajax-loader.gif" ' +
                'width="54" height="55" vspace="15" alt=""><br><br><br>' +
                '<b><i>Загружается...<\/i><\/b><\/div>'
    });
} catch (e) {}

function countSeconds(count)
{
    var msg = count + " секунд";
    var a = parseInt(((count % 100) / 10));
    var b = parseInt((count % 10));

    var end = '';
    switch (b) {
        case 1: end = 'у'; break;

        case 2:
        case 3:
        case 4: end = 'ы'; break;

        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
        case 0: end = ''; break;
    }

    if (a == 1) {
        end = '';
    }

    return msg + end;
}

