var e;

function basket(html)
{
	e = window.open(html, 'html', 'scrollbars=yes,width=600,height=400');
	if (window.focus) { e.focus(); }

	return false;
}

function go(url)
{
	if (opener) {
		opener.window.location.href = url;
		opener.focus();
	}

	return false;

}

function takefocus(obj) {
	obj.focus();
}

var p;

function img(url, title, x, y)
{
    if (p) { p.close(); }

    p = window.open('', 'cover', 'scrollbars=no,width=' + x +',height=' + y);

    p.document.open();
    p.document.write('<html><head><title>' + title + '</title></head><body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">');
    p.document.write('<img id="img" src="' + url + '" alt="' + title + '" title="' + title + '" onclick="window.close();"><br>');
    p.document.close('</body></html>');

    if (window.focus) { p.focus(); }



    return false;
}

function rus()
{
	e = window.open("/info/translate/?popup=1", 'rus', 'scrollbars=no,width=400,height=300');
	if (window.focus) { e.focus(); }

	return false;
}

function sshot (url, src, title, x, y)
{

    var shot = document.getElementById('screenshot');
    shot.src = url;

    return false;
}



/*
Объект Ajax

Пример:
    function Success(req,options) {
        if (req.requestIsSuccess) 
            alert(req.responseText);
        }
    }
    var req = new RAjaxRequest( {'url': '/test.html', params: 'aa=bb', callback:Success } );

Параметры: 
    url:	url запроса.
    asynch:	true|false. Флаг фиснхронности запроса. (default - true)
    method:	post|get. HTTP-метод запроса. (default - get)
    contentType: Content-Type запроса для метода post. (default - application/x-www-form-urlencoded )
    params:	параметры запроса. Для метода get - строка uri. Для метода post - тело запроса.
    headers:	{}. Дополнительные заголовки HTTP-запроса.
    callback:	функция, которая будет вызвана по окончанию обработки запроса. На вход передается два аргумента. 
        Первый - объект XMLHttpRequest, второй - набор параметров, переданных в объект RAjaxRequest.

*/

function RAjaxRequest(args) { 
    this.requestSetOptions(args);
    this.requestMakeTransport();
    this.requestSend();
}
(function() {
    RAjaxRequest.prototype = { 
        options: {
            asynch: true,
            method: 'get',
            contentType: 'application/x-www-form-urlencoded',
            params: '',
            url: '',
            headers: {},
            callback: null
        },
        transport: null,
        ActiveXObjects: [ 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP' ],

        // установка аттрибутов
        requestSetOptions: function(args) {
            for (var e in args) { this.options[e] = args[e]; }
        },

        // функция создания XMLHttp объекта
        requestMakeTransport: function() {
            var xObj = null;
            try {
                xObj = new XMLHttpRequest();
            } catch(e) {
                for (var i=0;i<this.ActiveXObjects.length;++i) {
                    try {
                        xObj = new ActiveXObject(this.ActiveXObjects[i]);
                        if (xObj) break;
                    } catch(e) {}
                }
            }
            this.transport = xObj;
        },

        // непосредственный вызов
        requestSend: function() {
            try {
                // onreadystatechange
                if (typeof(this.options.callback)=='function') {
                    var thisObj = this;
                    this.transport.onreadystatechange = function() {
                        if (thisObj.transport.readyState==4) {
                            thisObj.transport.onreadystatechange = function(){};
                            thisObj.options.callback(thisObj.transport, thisObj.options);
                        }
                    };
                }

                var params = this.options.params || '';
                if (this.options.method == 'get' && params.length > 0)
                    this.options.url += (this.options.url.match(/\?/) ? '&' : '?') + params.replace(new RegExp('\\+','g'), '%2B') + '&_=';

                this.transport.open(this.options.method.toUpperCase(), this.options.url, this.options.asynch);

                // установка http заголовков
                var requestHeaders = this.options.headers;
                requestHeaders['X-Requested-With'] = 'XMLHttpRequest';

                // for post method
                if (this.options.method == 'post') requestHeaders['Content-type'] = this.options.contentType;
                // for mozilla bugs
                if (this.transport.overrideMimeType) requestHeaders['Connection'] = 'close';

                for (var e in requestHeaders) {
                    this.transport.setRequestHeader(e, requestHeaders[e]);
                }

                this.transport.send(this.options.method == 'post' ? this.options.params : null);

            } catch(e) {}
        },

        // проверка на правильность ответа
        responseIsSuccess: function() {
        	try { if (this.transport.status==200) return true; } catch(e) {}
        	return false;
        }
    }
})();

var viewVisitingTimeOut;
var closeVisitingTimeOut;
var lastPositionVisitingFloatBlock = {};

var rFloatBlockId = 'info_float_block';

// ajax запрос блока и его визуализация
function info_open(el, id) {
    var url = '/region/export/';
    url += '?id='+id+'&r='+Math.random();

    var req = new RAjaxRequest( {'url': url, callback: function(r, options){
        if ( req.responseIsSuccess ) {
            if (r.responseText) {

		info_close();

                var infoFloatBlock = document.createElement('div');
                infoFloatBlock.setAttribute('id', rFloatBlockId);
                try {
                    infoFloatBlock.attachEvent('onmouseover', eventMouseOverInfoFloatBlock);
                    infoFloatBlock.attachEvent('onmouseout', eventMouseOutInfoFloatBlock);
                } catch (e) {
                    try {
                        infoFloatBlock.setAttribute('onmouseover', 'eventMouseOverInfoFloatBlock();');
                        infoFloatBlock.setAttribute('onmouseout', 'eventMouseOutInfoFloatBlock();');
                    } catch (e) {}
                }

                infoFloatBlock.innerHTML = r.responseText;
                document.body.appendChild(infoFloatBlock);
                infoFloatBlock.style.display = 'block';
                infoFloatBlock.style.position = 'absolute';

                var infoFloatBlockWH = el_get_dimensions(infoFloatBlock);
                var infoFloatBlockXY = el_get_position(el);

                infoFloatBlockXY.y = parseInt(infoFloatBlockXY.y) - infoFloatBlockWH.h - 10;
                el_move(infoFloatBlock, parseInt(infoFloatBlockXY.x), parseInt(infoFloatBlockXY.y));
            }
        }
     } } );
}

function eventMouseOverInfoFloatBlock() {
        window.clearTimeout(closeVisitingTimeOut);
}

function eventMouseOutInfoFloatBlock() {
        info_close(true);
}

function info_close(flag_timeout) {
        window.clearTimeout(viewVisitingTimeOut);
        window.clearTimeout(closeVisitingTimeOut);
        if (flag_timeout) {
                closeVisitingTimeOut = window.setTimeout("info_close_timeout();", 500);
        } else {
                info_close_timeout();
        }
}


function el_move(el, left, top) {
        if (!el) return false;
        el.style.left = left + "px";
        el.style.top = top + "px";
}

function el_get_dimensions(el) {
        if (el.style.display != 'none') {
              return {w:el.offsetWidth,h:el.offsetHeight};
        }
        return {w:el.clientWidth,h:el.clientHeight};
}

function el_get_position(el) {
	var x = 0, y = 0;
	do {
		y += el.offsetTop  || 0;
		x += el.offsetLeft || 0;
		el = el.offsetParent;
	} while (el);

	if (navigator.userAgent.indexOf ("Opera") != -1){
    	    y = window.event.y+document.body.scrollTop;
        }
                                                                
	return {x:x,y:y};
	
}

function info_close_timeout() {
        var infoFloatBlock = document.all ? document.all[rFloatBlockId] : document.getElementById(rFloatBlockId);
        if (!infoFloatBlock) return false;
        infoFloatBlock.parentNode.removeChild(infoFloatBlock);
        lastPositionVisitingFloatBlock = {};
}
