function addBookmark(url, title)  
{
    if (!url) url = location.href;
    if (!title) title = document.title;

    //Gecko
    if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) window.sidebar.addPanel (title, url, "");
    //IE4+
    else if (typeof window.external == "object") window.external.AddFavorite(url, title);
    //Opera7+
    else if (window.opera && document.createElement)
    {
      var a = document.createElement('A');
      if (!a) return false; //IF Opera 6
      a.setAttribute('rel','sidebar');
      a.setAttribute('href',url);
      a.setAttribute('title',title);
      a.click();
    }
    else return false;

    return true;
}

function buildTree(id, typ_id, mod_id) 
{            
    document.getElementById('tree' + id).style.display = 'block';
    if (Ext.get('tree-panel-' + id) != null)
        return;
    
    var arr = Cookie.read('openedTree');
    if (arr == null)
        arr = ['item' + id];
    if (typeof arr != 'object') 
        arr = [arr];
    if (!arr.contains('item' + id)) 
        arr[arr.length] = 'item' + id;
    Cookie.write('openedTree', arr);
        
    Ext.BLANK_IMAGE_URL = "/files/ext/img/s.gif";
    var treePanel = new Ext.tree.TreePanel({
        id          : 'tree-panel-' + id,
        renderTo    : 'tree' + id, 
        autoScroll  : true,
        border      : false,
    
        rootVisible : false,
        lines       : true,
    
        dataUrl: '/td_loader.php?cmd=structure&typ_id=' + typ_id,
    
        root: {
            nodeType: 'async',
            text    : 'Легковые автомобили',
            id        : 'node-' + id,
            expanded : true
        },
    
        listeners   : {
            click : function(n)
            {
                if (n.leaf) 
                    document.location = '/spares/' + mod_id + '/' + typ_id + '/' + n.id.replace('node-', '');
                else
                    n.expand();    
            },
            load  : function(node)
            {
                if (node.id == 'node-' + id)
                {
                    Ext.get('treeLoader' + id).setVisibilityMode(Ext.Element.DISPLAY);
                    Ext.get('treeLoader' + id).hide();
                }    
            }
        }
    });
}

function showPopup(url, title, w, h)
{
    window.open(url, title, 'status=no,scrollbars=no,resizable=yes,width=' + w + ',height=' + h);
    return false;
}

function expandAll()
{
    $$('div.spares').each(function(item) {
        item.onclick();
    });
}

function collapseAll()
{
    $$('div.spares').each(function(item) {
        var ids = item.id.split('_');        
        document.getElementById('tree' + ids[1]).style.display = 'none';
    });
    Cookie.dispose('openedTree');
}

function initTree()
{
    var arr = Cookie.read('openedTree');
    if (arr != null) {
        arr = arr.split(',');
        arr.each(function(item) {
            var id = item.replace('item', '');
            document.getElementById('spare_' + id).onclick();
        });
    } else {
        $$('div.spares')[0].onclick();
    }
}


function addToCart(la_art_id, prices) 
{
	var exists = prices.length > 0;
	if (exists) {
		yaCounter1240755.hit('#goToBasket', 'Нажатие на кнопку Цены / По заказу');
	} else {
		yaCounter1240755.hit('#goToBasketPrice', 'Нажатие на кнопку Цены / С ценами');
	}
	var store =  new Ext.data.SimpleStore({
		fields: [ {name : 'price', type: 'float'}, 'srock', 'stock', 'code', 'supplier', 'name'],
		sortInfo : { field : 'price', direction : 'ASC' }
	});
	store.loadData(prices);
	var sm = new Ext.grid.CheckboxSelectionModel();
	var win = new Ext.Window({
		title 	: 'Добавление в корзину',
		width	: exists ? 800 : 400,
		modal	: true,
		waitMsgTarget : true,
		bodyStyle : 'padding: 10px; color: #000;',
		html 	: '<div style="margin: 10px 3px 0 3px;">Всю информацию вы можете уточнить по телефону: ' + 
					(!exists ? '<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' : '') + 
					'<strong>+7 (812) 730-19-32</strong>' + 
					(!exists ? '<br/><br/>Мы предлагаем данную запасную часть добавить в заказ для дальнейшего оформления и согласнования с нашими менеджерами.' : '' + '</div>'),
		items   : [{
			id : 'grid',
			hidden : !exists,	   
			xtype : 'grid',
			height: 300,
			autoExpandColumn : 'common',
			store : store,
			sm: sm,
			columns : [sm, {
				header : 'Код',
				dataIndex : 'code',
				width : 150,
				sortable : true
			}, {
				id			: 'common',
				header 		: 'Наименование',
				dataIndex 	: 'name',
				sortable : true
			}, {
				header : 'Цена, руб.',
				align : 'right',
				dataIndex : 'price',
				sortable : true
			}, {
				header : 'Наличие',
				align : 'right',
				dataIndex : 'stock',
				sortable : true,
				renderer : function(v, o, r) {
					return r.data.stock != '' ? r.data.stock : r.data.srock;
				}
			}]
		}],
		buttons : [{
			text 	: 'Отменить',
			handler : function() {
				win.close();
			}
		}, {
			text 	: 'Добавить' + (exists ? ' выделенное' : ''),
			handler : function() {
				if (!exists) {
					yaCounter1240755.hit('#addToBasket', 'Добавление в корзину / По заказу');
					Ext.Ajax.request({
						url		: '/basket.php',
						params	: {
							'GID' 	: la_art_id,
							'GCNT' 	: 1,
							'ZAKAZ' : '',
							'cIdx' : 0,
							'cTotal' : 1
						},
						success : function() {
							document.location.reload();	
						}
					});
				} else {
					yaCounter1240755.hit('#addToBasketPrice', 'Добавление в корзину / С ценами');
					var rows = Ext.getCmp('grid').getSelectionModel().getSelections(); 
					if (rows.length == 0) {
						Ext.Msg.alert('Ошибка', 'Выберите хотя бы одну позицию для добавления');	
						return;
					}
					var mask = new Ext.LoadMask(Ext.getBody(), {msg:"Добавление товаров в корзину..."});
					mask.show();
					var idx = 0;
					for(var i = 0; i < rows.length; i++) {					
						Ext.Ajax.request({
							url		: '/basket.php',
							params	: {
								'GID' 	: la_art_id,
								'GCNT' 	: 1,
								'ZAKAZ'	: rows[i].get('code'),
								'cIdx' : i,
								'cTotal' : rows.length
							},
							success : function(response) {
								response = Ext.decode(response.responseText);
								if (response.isLast) {
								 	mask.hide();
									document.location.reload();
								}
							}
						});
						idx++;
					}
				}
			}
		}]				 
	});
	win.show();
}
