var showImg = true;
var item_url = 'http://images.ganjawars.ru/img/items/';

var dirty_eun = 0;
var clean_eun = 0;
var items_weight = 0;
var items_count = 0;

var tip = document.createElement("DIV");

// инициализация
function init()
{
    
    tip.setAttribute("id", "tooltip");
    document.body.appendChild(tip);
    
    
    // добавление предметов
    for (gw_item in items) {
        if (items[gw_item].art == 1) {
            var div = document.createElement('DIV');
            var p = document.createElement('P');
            var img = document.createElement('IMG');
            
            // название предмета
            var item_name = document.createTextNode(items[gw_item].name);
            
            // картинка
            if (showImg) {
                img.setAttribute('src',item_url + gw_item +'_s.jpg');
                img.setAttribute('id',gw_item);
                img.setAttribute('alt','');
                add_event(img,'click',add_item);
                div.appendChild(img);
                
                add_tooltip(img,gw_item);
            }
            
            // текст
            p.appendChild(item_name);
            p.setAttribute('id',gw_item);
            add_event(p,'click',add_item);
            div.appendChild(p);
            
            document.getElementById('items').appendChild(div);
        }
    }
}

function add_tooltip(obj,gw_item)
{
    // tooltip
    img_alt = document.createElement('DIV');
    img_alt.setAttribute('id','item_'+ gw_item);
    
    // заголовок
    _p_title = document.createElement('P');
    _p_title.appendChild(document.createTextNode(items[gw_item].name));
    _p_title.className = 'title';
    img_alt.appendChild(_p_title);
    
    // картинка
    _img = document.createElement('IMG');
    _img.setAttribute('src',item_url + gw_item +'.jpg');
    _img.setAttribute('alt','');
    _img.className = 'tooltip';
    img_alt.appendChild(_img);
    
    // стоимость
    _cost_div = document.createElement('DIV');
    _cost_div.className = 'left';
    _cost = document.createElement('P');
    _cost.className = 'title';
    _cost.appendChild(document.createTextNode('Стоимость:'));
    _cost_div.appendChild(_cost);
    _pc = document.createElement('P');
    _pd = document.createElement('P');
    _pd.innerHTML = '<span class="dirty_eun">'+ items[gw_item].cost_eun +'</span> EUN &laquo;грязными&raquo;';
    _pc.innerHTML = '<span class="clean_eun">'+ calcCleanEun(items[gw_item].cost_eun) + '</span> EUN &laquo;чистыми&raquo;';
    
    _cost_div.appendChild(_pd);
    _cost_div.appendChild(_pc);
    
    // вес
    _weight = document.createElement('P');
    _weight.innerHTML = '<span class="title">Вес предмета: </span>'+ items[gw_item].weight;
    _cost_div.appendChild(_weight);
    
    // прочность
    _durab = document.createElement('P');
    _durab.innerHTML = '<span class="title">Прочность: </span>'+ items[gw_item].durability;
    _cost_div.appendChild(_durab);
    
    img_alt.appendChild(_cost_div);
    
    ToolTip(obj,img_alt);
}

function add_event(o,e,a)
{
    if (o.addEventListener) {
        o.addEventListener(e, a, false);
    } else if (o.attachEvent) {
        o.attachEvent("on" + e, a);
    } else return null;
}

// добавление предмета
function add_item(event)
{
    var o = window.event ? window.event.srcElement : event.target;
    if (!o.id) return null;
    
    // визуальное представление предмета
    var p = document.createElement('P');
    var item_name = document.createTextNode(items[o.id].name);
    
    p.appendChild(item_name);
    p.setAttribute('title',o.id);
    add_event(p,'click',remove_item);
    document.getElementById('content').appendChild(p);
    
    add_tooltip(p,o.id);
    
    // добавление к стоимости
    dirty_eun += items[o.id].cost_eun;
    clean_eun += calcCleanEun(items[o.id].cost_eun);
    
    // добавление к весу и количеству
    items_weight += items[o.id].weight;
    items_count += 1;
    
    updateCalc();
}

// удаление предмета
function remove_item(event)
{
    var o = window.event ? window.event.srcElement : event.target;
    if (!o.getAttribute('title')) return null;
    
    // убираем предмет из списка
    items_count -= 1;
    o.parentNode.removeChild(o);
        
    var gw_item = o.getAttribute('title');
    
    // вычитаем из общей стоимости
    dirty_eun -= items[gw_item].cost_eun;
    clean_eun -= calcCleanEun(items[gw_item].cost_eun);
    
    // вычитаем вес
    items_weight -= items[gw_item].weight;
    
    if (tip.firstChild) {
        tip.removeChild(tip.firstChild);
        tip.style.visibility = "hidden";
    }
    
    updateCalc();
}

// обновление еунов
function updateCalc()
{
    document.getElementById('dirty_eun').firstChild.nodeValue = dirty_eun;
    document.getElementById('clean_eun').firstChild.nodeValue = clean_eun;
    document.getElementById('items_weight').firstChild.nodeValue = items_weight;
    document.getElementById('items_count').firstChild.nodeValue = items_count;
}

// расчет чистых еунов
function calcCleanEun(eun)
{
    return Math.floor(eun * 0.9);
}

// очистка списка предметов
function clearItems()
{
    dirty_eun = 0;
    clean_eun = 0;
    items_weight = 0;
    items_count = 0;
    
    updateCalc();
    
    var o = document.getElementById('content');
    var p = o.getElementsByTagName("P");
    pLength = p.length;
    for (i = pLength - 1;i >= 0; i--) {
        o.removeChild(p[i]);
    }
}

function ToolTip(obj, text) {
    
  
    obj.onmouseout = function(e) {
        tip.removeChild(tip.firstChild);
        tip.style.visibility = "hidden";
    };
    
    obj.onmousemove=function(e) {
        tip.appendChild(text);
        oCanvas = document.getElementsByTagName(
			(document.compatMode && document.compatMode == "CSS1Compat") ? "HTML" : "BODY"
			)[0];
		x = window.event ? event.clientX + oCanvas.scrollLeft : e.pageX;
		y = window.event ? event.clientY + oCanvas.scrollTop : e.pageY;
		
        w_width = oCanvas.clientWidth ? oCanvas.clientWidth + oCanvas.scrollLeft : window.innerWidth + window.pageXOffset;
		w_height = window.innerHeight ? window.innerHeight + window.pageYOffset : oCanvas.clientHeight + oCanvas.scrollTop; 

		t_width = tip.offsetWidth;
		t_height = tip.offsetHeight;

		tip.style.left = x + 15 + "px";
		tip.style.top = y + 15 + "px";
		
		if (x + t_width > w_width) tip.style.left = w_width - t_width + "px";
		if (y + t_height > w_height) tip.style.top = w_height - t_height + "px";
        
        tip.style.visibility = "visible";
    }
}