var ELEMENT_NODE = 1;
var TEXT_NODE = 3;

function getCursorPosition(e)
{
	var x = 0, y = 0;
	
	if (!e) {
	    e = window.event;
	}
	
	if (e.pageX || e.pageY)	{
		x = e.pageX;
		y = e.pageY;
	} else if (e.clientX || e.clientY) {
		x = e.clientX + getBodyScrollLeft();
		y = e.clientY + getBodyScrollTop();
	}
	
    return {x: x, y: y};
}

function getElementPosition(e) {
    var x = 0, y = 0;
    while (e) {
        x += e.offsetLeft;
        y += e.offsetTop;
        e = e.offsetParent;
    }
    return {x: x, y: y};
}

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 getClientWidth(win)
{
	var w = 0;
	
    if (!win) {
        win = window.window;
    }
    
	if (win.self.innerHeight) {
	    w = win.self.innerWidth;
	} else if (win.document.documentElement && win.document.documentElement.clientWidth) {
	    w = win.document.documentElement.clientWidth; 
	} else if (win.document.body) {
	    w = win.document.body.clientWidth;
	}

	return w;
}

function getClientHeight(win)
{
	var h = 0;

	if (!win) {
        win = window.window;
    }
    
	if (win.self.innerHeight) {
	    h = win.self.innerHeight;
	} else if (win.document.documentElement && win.document.documentElement.clientHeight) {
	    h = win.document.documentElement.clientHeight; 
	} else if (win.document.body) {
	    h = win.document.body.clientHeight;
	}

	return h;
}

function openDialog(url, width, height)
{
    if (window.showModelessDialog) {
        var prop = 'dialogWidth: ' + width + 'px; dialogHeight: ' + height + 'px; resizable: no; center: yes; scroll: no; help: no; status: no; edge: raised;';
        var w = window.showModelessDialog(url, '', prop);
        w.resizeTo(width, height);
    } else {
        var w = window.open(url, '_blank', 'resizable, scrollbars, status, width=' + width + ', height=' + height + ', modal');
        parent_w = getClientWidth();
        parent_h = getClientHeight();
/*        win_w = getClientWidth(w);
        win_h = getClientHeight(w);
        alert([parent_w, parent_h, win_w, win_h]);*/
        w.moveTo((parent_w - width) / 2, (parent_h - height) / 2);
        w.resizeTo(width, height);
        w.focus();
    }
}


function openWindow(url, width, height)
{
    var w = window.open(url, '_blank', 'width=' + width + ', height=' + height + ', modal');
    parent_w = getClientWidth();
    parent_h = getClientHeight();
/*        win_w = getClientWidth(w);
    win_h = getClientHeight(w);
    alert([parent_w, parent_h, win_w, win_h]);*/
    w.moveTo((parent_w - width) / 2, (parent_h - height + 100) / 2);
    w.resizeTo(width, height);
    w.focus();
}

function node2element(node)
{
    switch (node.nodeType) {
        case ELEMENT_NODE:
            var element = document.createElement(node.nodeName);
            element.nodeValue = node.nodeValue;
            for (var i = 0; i < node.attributes.length; i ++) {
                element.setAttribute(node.attributes[i].name.toLowerCase(), node.attributes[i].value);
            }
            for (var i = 0; i < node.childNodes.length; i ++) {
                element.appendChild(node2element(node.childNodes[i]));
            }
            break;
        default:
        case TEXT_NODE:
            var element = document.createTextNode(node.nodeValue);
            break;
    }
    return element;
}

function is_browser_ie()
{
    var isDOM = document.getElementById; //DOM1 browser (MSIE 5+, Netscape 6, Opera 5+)
    var isOpera = isOpera5 = window.opera && isDOM; //Opera 5+
    var isOpera6 = isOpera && window.print; //Opera 6+
    var isOpera7 = isOpera && document.readyState; //Opera 7+
    var isMSIE = document.all && document.all.item && !isOpera; //Microsoft Internet Explorer 4+
    var isMSIE5 = isDOM && isMSIE; //MSIE 5+
    var isNetscape4 = document.layers; //Netscape 4.*
    var isMozilla = isDOM && navigator.appName=="Netscape"; //Mozilla или Netscape 6.*
    return isMSIE;
}

function is_browser_opera()
{
    var isDOM = document.getElementById;
    return (window.opera && isDOM);
}

function str2date(str)
{
    var regexp = new RegExp('^([0-9]{1,2})[\.\/\-]([0-9]{1,2})[\.\/\-]([0-9]{2,4})$');
    if (date = regexp.exec(str)) {
        for (var i = 1; i < 3; i ++) {
            for (var j = 0; j < (4 - date[i].length); j ++) {
                date[i] = '0' + date[i];
            }
        }
        return date[3] + '' + date[2] + '' + date[1];
    } else {
        return null;
    }
}

function weekday(d, m, y)
{
    var date = new Date(y, m - 1, d);
    return date.getDay();
}

function leap_year(year)
{
    return year % 4 ? false : (year % 100 ? true : (year % 400 ? false : true));
}

function format_date(day, month, year)
{
    if (day.toString().length == 1) {
        day = '0' + day;
    }

    if (month.toString().length == 1) {
        month = '0' + month;
    }

    if (year.toString().length == 2) {
        year = ((parseInt(year) < 50 ) ? '20' : '19') + year;
    }
    
    return day + '/' + month + '/' + year;
}

/********************
    auto complete
********************/
var process_id = 0;
var auto_complete_container = null;
var auto_complete_current = null;
var auto_complete_value = null;
var hide_auto_complete = true;

function auto_complete(event, caller, source)
{
    if (window.event) event = window.event;
    var key_code = event.keyCode ? event.keyCode : event.which ? event.which : null;
    switch (key_code) {
        case 38:
            //up
            if (auto_complete_current && auto_complete_current.previousSibling) {
                auto_complete_current.className = 'auto-complete-item';
                auto_complete_current = auto_complete_current.previousSibling;
                auto_complete_current.className = 'auto-complete-item-hover';
            }
            break;
        case 40:
            //down
            if (auto_complete_current && auto_complete_current.nextSibling) {
                auto_complete_current.className = 'auto-complete-item';
                auto_complete_current = auto_complete_current.nextSibling;
                auto_complete_current.className = 'auto-complete-item-hover';
            }
            break;
        case 13:
            //choose
            if (auto_complete_current && auto_complete_container) {
                auto_complete_choose(auto_complete_current.innerHTML, caller);
            }
            break;
        default:
            //if (!auto_complete_container) {
                if (caller.value != auto_complete_value) {
                    auto_complete_value = caller.value;
                    auto_complete_init(caller, source);
                }
            //}
            //window.status = key_code;
    }
    //alert([key_code, event.keyCode, event.which]);
}

function auto_complete_init(caller, source)
{
    clearTimeout(process_id);
    process_id = setTimeout(function() {auto_complete_search(caller, source)}, 500);
}

function auto_complete_search(caller, source)
{
    var reg_source = new RegExp('([a-z-_]+):([a-z-_]+)', 'i');
    if (parts = reg_source.exec(source)) {
        switch (parts[1]) {
            default:
            case 'cases':
                var url = '/uzinvest/module/auto-complete/?target=' + parts[2];
                break;
        }
    }
    url += '&search=' + caller.value;
    
    if (window.XMLHttpRequest) {
        var req = new XMLHttpRequest();
        req.onreadystatechange = function () {auto_complete_set(req, caller)};
        req.open('GET', url, true);
        req.send(null);
        document.body.style.cursor = 'wait';
    } else if (window.ActiveXObject) {
        var req = new ActiveXObject('Microsoft.XMLHTTP');
        req.onreadystatechange = function () {auto_complete_set(req, caller)};
        req.open('GET', url, true);
        req.send();
        document.body.style.cursor = 'wait';
    } else {
        alert('XMLHttpRequest is disabled in your browser');
    }
}

function auto_complete_set(req, caller)
{
    if (req.readyState == 4 && req.status == 200) {
        var response = req.responseXML;
        if (!response) {
            alert(req.responseText);
        }
        
        var container = document.createElement('UL');
        caller.parentNode.insertBefore(container, caller.nextSibling ? caller.nextSibling : caller);
        container.className = 'auto-complete-container';
        container.style.width = (caller.offsetWidth - 5) + 'px';
        container.onmouseover = function() {
            hide_auto_complete = false;
        }
        container.onmouseout = function() {
            hide_auto_complete = true;
        }

        var caller_pos = getElementPosition(caller);
        container.style.left = (caller_pos.x + 5) + 'px';
        container.style.top = (caller_pos.y + caller.offsetHeight) + 'px';
        
        var samples = response.getElementsByTagName('sample');
        for (var i = 0; i < samples.length; i ++) {
            var item = document.createElement('LI');
            container.appendChild(item);
            item.innerHTML = samples[i].firstChild ? samples[i].firstChild.nodeValue : '---';
            item.className = 'auto-complete-item';
            item.onmouseover = function () {
                if (auto_complete_current) {
                    auto_complete_current.className = 'auto-complete-item';
                }
                auto_complete_current = this;
                this.className = 'auto-complete-item-hover';
            }
            /*item.onmouseout = function () {
                this.className = 'auto-complete-item';
            }*/
            item.onclick = function () {
                auto_complete_choose(this.innerHTML, caller);
            }
        }
        
        if (auto_complete_container) {
            auto_complete_container.parentNode.removeChild(auto_complete_container);
        }
        
        if (container.firstChild) {
            auto_complete_current = container.firstChild;
            auto_complete_current.className = 'auto-complete-item-hover';
        } else {
            auto_complete_current = null;
        }
        auto_complete_container = container;
        caller.onblur = function() {
            if (hide_auto_complete) {
                auto_complete_destroy();
            }
        }
        document.body.style.cursor = 'default';
    }
}

function auto_complete_choose(value, input)
{
    input.value = value;
    auto_complete_value = value;
    auto_complete_destroy();
}

function auto_complete_destroy()
{
    if (auto_complete_container) {
        auto_complete_container.parentNode.removeChild(auto_complete_container);
        auto_complete_container = null;
        auto_complete_value = null;
    }
}
