var timerId = false;

// Отображение прогресс-бара
function showProgress(obj) {
    // прогресс
    var progress = document.getElementById('progress');
    var p_obj = getPosition(obj);
    progress.style.left = (p_obj.left - 5) + 'px';
    progress.style.top = p_obj.top + 'px';
    progress.className = 'visible';
}
function hideProgress() {
    document.getElementById('progress').className = 'hidden';
}

// Версия для печати
function printPage(obj)
{
    var content = obj.parentNode;

    var w = window.open('','props_window','top=0, left=20,scrollbars=1, menubar=0, toolbar=0, location=0, directories=0, status=1, resizable=1,width=900,height=600');
    w.focus();
    
    w.document.write('<html><link rel="stylesheet" type="text/css" href="/css/print.css"><body onload="opener.endPrint(this)">'+content.innerHTML+'<script language="javascript" type="text/javascript" src=""></script></body></html>');
    w.document.close();
}
function endPrint(w)
{    
    // Скрываем лишнее
    var content = w.document.body;
    for(var i=0; i < content.childNodes.length; i++) {
        if (content.childNodes[i].className == 'print' || content.childNodes[i].id == 'path') {
            content.childNodes[i].innerHTML = '';
            content.childNodes[i].style.visibility = 'hidden';
            content.childNodes[i].style.display = 'none';
        }
    }
    w.print();
    w.close();
    return false;
}
// Вывод всплывающего меню
function showPmenu(obj)
{    return false;
        // ID категории
    var id = obj.href.match(/[0-9]+/);
    if (id == null) return false;
        var pmenu = document.getElementById('pmenu');
    var pos = getPosition(obj);
    pmenu.style.left = (pos.left + 70) + 'px';
    pmenu.style.top = (pos.top + 20) + 'px';
    // Устанавливаем таймер
    if (timerId) clearTimeout(timerId);
    timerId = setTimeout('hidePmenu()', 3000);
    
    // Содержание выпадающего меню
    var div = document.getElementById('c'+id);
    if (div) {        pmenu.className = "pmenu visible";
        if (div.className != 'visible') {
            var elems = div.getElementsByTagName('A');
            var str = '';
            for(var i=0; i<elems.length; i++) {                str += '<a href="'+elems[i].href+'">- '+elems[i].innerHTML+'</a>';
            }
            div.innerHTML = str;
            div.className = 'visible';
        }
                document.getElementById('cc').innerHTML = div.innerHTML;
    } else {
        hidePmenu();
    }    
}
function hidePmenu()
{    document.getElementById('pmenu').className = "hidden";
    if (timerId) clearTimeout(timerId);
}
function pmenuOver()
{
    if (timerId) clearTimeout(timerId);
}
function pmenuOut()
{
    if (timerId) clearTimeout(timerId);
    timerId = setTimeout('hidePmenu()', 1000);
}
function checkCategory(obj) {    return true;    // ID категории
    var id = obj.href.match(/[0-9]+/);
    if (document.getElementById('c'+id)) return false; else return true;
}

// Открытие подменю
function subCat(id)
{    var div = document.getElementById('c'+id);
    if (div) {        if (div.innerHTML) {            div.className = div.className == 'hidden' ? 'visible' : 'hidden';
        
            // Закрываем остальные
            /*
            var elems = div.parentNode.getElementsByTagName('div');
            for(var i=0; i<elems.length; i++) {                if (elems[i] != div && elems[i].className == 'visible') {                    elems[i].className = 'hidden';
                }
            }
            */
            return false;
        } else {            return true;
        }
    } else {        alert('Nooooo!');
        return true;
    }
}
function showCategoriesActions(obj)
{    //action_categories    var elems = obj.parentNode.getElementsByTagName('A');
    
    for(var i=0; i<elems.length; i++) {        // Верхний уровень        if(elems[i].parentNode == obj.parentNode) {            var id = elems[i].href.match(/[0-9]+/);            var sub = document.getElementById('c'+id);
            var empty = true; // категория пуста (дефолт)
                        if (sub != 'undefined') {                for(var j=0; j<sub.childNodes.length; j++) {                    if (sub.childNodes[j].href.match(action_categories) == null) {                        sub.childNodes[j].className = 'hidden';
                        alert(sub.childNodes[j].href);
                    } else {                        empty = false;
                    }
                }
                //alert(sub.childNodes.length);                //alert(sub.childNodes.length);
            } else if (1) {                
            }
        }        if (elems[i].href.match(action_categories) == null)
        {            //alert(1);
        }
    }
    
}

/* Скролл картинок */
var k = 2;
window.onload = function() {
    var tables = document.getElementsByTagName('TABLE');
    
    var t = null;
    
    for(var i=0; i<tables.length; i++) {        if (tables[i].id != 'tscroll') continue;
        
        var is = tables[i].getElementsByTagName('I');
        var spans = tables[i].getElementsByTagName('SPAN');
        
        // Ищем скролл и др.
        for(var j=0; j<is.length; j++) {
            if (is[j].id == 'thumb') {
                for(var jj=0; jj<spans.length; jj++) {
                    if (spans[jj].id == 'images-block') {
                        t = new tDrag();
                        t.init(is[j], null, spans[jj], 0, 0, 0, 135);
                        
                        is[j].k  = ((spans[jj].parentNode.scrollHeight - 205) * 0.0074);
                        
                        // если картинки все умещаются
                        if (spans[jj].parentNode.scrollHeight <= 245){
                            var scroll = is[j];
                            while (scroll.id != 'scroll') scroll = scroll.parentNode;
                            scroll.className = 'hidden';
                            break;
                        }
                        // Сохраняем управляемый объект
                        is[j].so = spans[jj];
                        
                        is[j].onDrag = function(x, y) {
                            this.so.style.top = y * (-this.k) +"px";
                        }
                        break;
                    }
                }
                break;
            }
        }        
    }
}

function scrollBtn(btn, obj)
{    var aThumb = obj.parentNode.childNodes[3].firstChild;
    var scrolldiv = obj.parentNode.childNodes[3].firstChild.so;
    
    // направление
    var v = btn == 0 ? -1 : 1;
    var tcont = scrolldiv.offsetTop - (50 * v);
    if (tcont >0){        scrolldiv.style.top = '0px';
        aThumb.style.top = '0px';
    } else if ((scrolldiv.scrollHeight + tcont - 245) < 0 && v > 0){
        scrolldiv.style.top = (scrolldiv.offsetHeight - 245) * -1 + 'px';
        aThumb.style.top = '135px';
        
    } else {        scrolldiv.style.top = tcont + 'px';
        aThumb.style.top = (tcont*-1*135/(scrolldiv.scrollHeight - 245)) + 'px';
    }
}

function tDrag() {    var o = null; // перемещаемый объект
    var so = null; // ведомый объект
	var Drag = null;
	
	this.init = function(elem, oRoot, subObj, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
    {        Drag = this;        o = elem;
        so = subObj;
        o.onmousedown    = this.start;
        
        o.hmode            = bSwapHorzRef ? false : true ;
        o.vmode            = bSwapVertRef ? false : true ;

        o.root = oRoot && oRoot != null ? oRoot : o ;

        if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
        if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
        if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
        if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

        o.minX    = typeof minX != 'undefined' ? minX : null;
        o.minY    = typeof minY != 'undefined' ? minY : null;
        o.maxX    = typeof maxX != 'undefined' ? maxX : null;
        o.maxY    = typeof maxY != 'undefined' ? maxY : null;

        o.xMapper = fXMapper ? fXMapper : null;
        o.yMapper = fYMapper ? fYMapper : null;

        o.root.onDragStart  = new Function();
        o.root.onDragEnd    = new Function();
        o.root.onDrag       = new Function();
    }
    this.tt = function() {alert(1)}
    this.start = function(e)
    {
        Drag.obj = o;
        e = Drag.fixE(e);
        
        var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
        var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
        o.root.onDragStart(x, y);

        o.lastMouseX    = e.clientX;
        o.lastMouseY    = e.clientY;

        if (o.hmode) {
            if (o.minX != null)    o.minMouseX    = e.clientX - x + o.minX;
            if (o.maxX != null)    o.maxMouseX    = o.minMouseX + o.maxX - o.minX;
        } else {
            if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
            if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
        }

        if (o.vmode) {
            if (o.minY != null)    o.minMouseY    = e.clientY - y + o.minY;
            if (o.maxY != null)    o.maxMouseY    = o.minMouseY + o.maxY - o.minY;
        } else {
            if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
            if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
        }

        document.onmousemove    = Drag.drag;
        document.onmouseup      = Drag.end;

        return false;
    }
    this.drag = function(e)
    {
        e = Drag.fixE(e);
        Drag.obj = o;

        var ey    = e.clientY;
        var ex    = e.clientX;
        var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
        var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
        var nx, ny;

        if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
        if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
        if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
        if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

        nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
        ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

        if (o.xMapper)        nx = o.xMapper(y)
        else if (o.yMapper)    ny = o.yMapper(x)

        Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
        Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
        Drag.obj.lastMouseX    = ex;
        Drag.obj.lastMouseY    = ey;

        Drag.obj.root.onDrag(nx, ny);
        return false;
    }
    this.end = function()
    {
        document.onmousemove = null;
        document.onmouseup   = null;
        Drag.obj.root.onDragEnd(    parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), 
                                    parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
        Drag.obj = null;
    }
    this.fixE = function(e)
    {
        if (typeof e == 'undefined') e = window.event;
        if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
        if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
        return e;
    }
}


// Показ картинки
function showImg(obj, mode)
{    // ищем таблицу текущей картинки
    var tbl = obj;
    while (tbl.tagName != 'TABLE' && tbl.tagName != 'BODY') tbl = tbl.parentNode;
    
    var elems = tbl.getElementsByTagName('DIV');
    for(var i=0; i<elems.length; i++) {        if (elems[i].id == 'mimg') {            var mimg = elems[i];
            break;
        }
    }
        var mimg_label = mimg.getElementsByTagName('i');
    var mimg_img   = mimg.getElementsByTagName('img');
    
    var mimg_size = mimg_img[0].src.match(/[0-9]+x[0-9]+/);
    var mimg_lable = mimg_label[0].innerHTML;
    var mimg_src = mimg_img[0].src;
    
    if (mode == 1){
        var obj_label = obj.getElementsByTagName('i');
        var obj_img   = obj.getElementsByTagName('img');

        mimg_img[0].src = obj_img[0].src.replace(/[0-9]+x[0-9]+/, mimg_size);
        mimg_label[0].innerHTML = obj_label[0].innerHTML;
        mimg_label[0].parentNode.className = obj_label[0].innerHTML == '' ? 'hidden' : 'visible';
        
        var vars = obj_img[0].src.match(/c([0-9]+)-i([0-9]+).jpg/);
        // Ищем блок с текстовым описанием картинки
        if ('undefined' != vars[1] && 'undefined' != vars[2] ){            
            var mdescr = document.getElementById('img_description_'+vars[1]);
            var descr = document.getElementById('id-'+vars[2]).innerHTML;
            if (descr != '') {                mdescr.innerHTML  = '<strong>' + obj_label[0].innerHTML + '</strong><br />';
                mdescr.innerHTML += descr;
            } else {                mdescr.innerHTML = '';
            }
        }
        
        
    } else {        var elems = mimg.parentNode.childNodes; //document.getElementById('popimg');
        for(var i=0; i<elems.length; i++) {
            if (elems[i].id == 'popimg') {
                var pimg = elems[i];
                // ищем картинку
                //pimg_img = pimg.getElementsByTagName('img');
                break;
            }
        }
        var img_src = mimg_src.replace(/img\/[0-9]+x[0-9]+\//, '');
        
        // Выводим картинку
        popImg(tbl, img_src);
    }
}

// Кладем товар в корзину
function putInCart(obj) {
	// таблица
	var tbl = obj;
    while (tbl.tagName != 'TABLE' && tbl.tagName != 'BODY') tbl = tbl.parentNode;
    
    // Ищем позицию элемента, на который мы нажали
	var pos = getPosition(obj);
    
    // ищем все элементы
    var products = '';
    var inputs = tbl.getElementsByTagName('INPUT');
    for(var i=0; i<inputs.length; i++) {        if (inputs[i].value.trim() != '' ? inputs[i].name.indexOf('count_') != -1 : false) {            if (products) products += '|';            products += inputs[i].name.replace(/count_/, '') + '=' + inputs[i].value.trim();
        }
    }
    // Если нечего класть в корзину
    if (products == '') {        alert('Необходимо ввести количество товаров');
        return false;
    }
	
	var ajax = new JsHttpRequest();

	ajax.open(null, '/ajax/eshop/cart.php', true);
    ajax.send( {'action':'put', 'products':products} );

	showProgress(obj);
    
    ajax.onreadystatechange = function() {
    	if (ajax.readyState == 4) {
    	    hideProgress();
    	    //document.getElementById('debug').innerHTML = ajax.responseText;
    	    var goods = ['наименований', 'наименование', 'наименования', 'наименования', 'наименования', 'наименований', 'наименований', 'наименований', 'наименований', 'наименований'];
    	    var pop_cart = document.getElementById('pop_cart');
    	    document.getElementById('cart_count').innerHTML = ajax.responseJS.count + ' ' + goods[lastNum(ajax.responseJS.count)];
    	    document.getElementById('cart_status').className = 'visible';
    	    pop_cart.className = 'pop_cart visible';
    	    pop_cart.style.top = pos.top - 20 + 'px';
        }
    }
}
function closePopCart()
{    document.getElementById('pop_cart').className = 'hidden';
    return false;
}
function refreshCart()
{    var frm = document.cart_frm;
    frm.action.value = 'update';
    frm.submit();
    return false;
}
// Проверка корзины
function checkCartFrm(obj)
{    var frm = document.cart_frm;
    var err = new Array();
    
    if (frm.phone.value.trim() == '' && frm.email.value.trim().match(/^[a-z0-9\-_\.]{1,100}@[a-z0-9\-_\.]{1,100}\.[a-z]{2,5}$/) == null) {        document.getElementById('err_contacts').className = 'err visible';
        return false;
    }
    
    showProgress(obj);
    
    return true;
}

 

