/**
* catalog.js
*/

var demandAjaxUrl = '/catalog/demand.ajax';
var demandImgUrl = '/resources/images/demand.png';

// demand
function demandPrice(cmd, p, q)
{
    var time = new Date().getTime();
    var data = {};
    var success;
    switch(cmd)
    {
        case 'append':
            data = {command : cmd, product : p, qty : q, time : time};
            success = appendSuccess;
            break;
        case 'remove':
            data = {command : cmd, product : p, time : time};
            success = removeSuccess;
            break;
        case 'clear':
            data = {command : cmd, time : time};
            success = clearSuccess;
            break;
        case 'list':
            data = {command : cmd, time : time};
            success = listSuccess;
            break;
    }

    $.ajax({
        url:demandAjaxUrl,
        type:'POST',
        async:true,
        data:data,
        dataType:'xml',
        cache:false,
        success:success
    });
}

// append
function appendSuccess(data, status)
{
    $('result',data).each(function()
    {
        if($('status', $(this)).text() == 'true')
        {
            demandPrice('list',null,null);
        }
    });
}

// remove
function removeSuccess(data, status)
{
    $('result',data).each(function()
    {
        if($('status', $(this)).text() == 'true')
        {
            demandPrice('list',null,null);
        }
    });
}

// clear
function clearSuccess(data, status)
{
    $('result',data).each(function()
    {
        if($('status', $(this)).text() == 'true')
        {
            demandPrice('list',null,null);
        }
    });
}

// list
function listSuccess(data, status)
{
    $('result',data).each(function()
    {
        if($('status', $(this)).text() == 'true')
        {
            if($('count', $(this)).text())
            {
                $('#demand-price-items').text($('count', $(this)).text());
            }
        }
    });
}

// activate field
function activateField(id)
{
    $('#catalog-demand #a-p-' + id).hide();
    $('#catalog-demand #i-p-' + id).show().focus();
    $('#catalog-demand #c-p-' + id).show();
}

// deactivate field
function deactivateField(id)
{
    $('#catalog-demand #a-p-' + id).show();
    $('#catalog-demand #i-p-' + id).hide();
    $('#catalog-demand #c-p-' + id).hide();
}

// change data
function changeData(id, obj)
{
    obj.value = parseInt(obj.value)

    if(obj.value == 'NaN')
    {
        obj.value = '';
    }
    else
    {
        obj.value = Math.abs(obj.value);
    }

    if(obj.value == 0)
    {
        $('#catalog-demand #a-p-' + id).html("<img src=\"" + demandImgUrl + "\" alt=\"Запросить цену\"/>");
        demandPrice('remove', id, null);
    }
    else
    {
        $('#catalog-demand #a-p-' + id).text(obj.value + ' шт.');
        demandPrice('append', id, obj.value);
    }
}

// update demand count
$(document).ready(function()
{
    demandPrice('list', null, null);
});

